tags:

views:

147

answers:

2

My question is how to set values to two attributes that have the same name but different namespaces.

Using C#, in an XML document, I need to assign two attributes to an element. It should look like

doc xmlns:xmi="uriaddress" element xsi:type="xsitype1" type="type1"

I tried

xElement.SetAttribute("type","uriaddress","xsitype1")

this works fine!

however, my surprise is that when I tried to set the second attribute, "type", by

xElement.SetAttribute("type","type1")

this works, but it also resets the attribute xmi:type to the same value as attribute "type", changing the element in an unintended way.

Now the element looks like

element xsi:type="type1" type="type1"

Any way to get around this?

A: 

Seems to me like you put the wrong namespace in the first SetAttribute call. That namespace should be the namespace for the xsi prefix, not for the xmi prefix...

You may just be trying to demonstrate the problem, so I might have gotten the wrong idea here

Hope that helps

LorenVS
Thanks for the attempt to answer. You were write in that just my illustration had a problem. THe namespace in the document is really xmlns:xsi="uriaddress"So unfortunately the question still remains.
+2  A: 

This code:

    XDocument d = new XDocument();
    XNamespace xsi = "uriaddress";
    d.Add(
        new XElement(
            "element",
            new XAttribute(XNamespace.Xmlns + "xsi", "uriaddress"),
            new XAttribute("type", "foo"),
            new XAttribute(xsi + "type", "bar")));
    using (XmlWriter xw = XmlWriter.Create(Console.Out))
    {
        d.WriteTo(xw);
    }

    d.Element("element").SetAttributeValue("type", "baz");
    using (XmlWriter xw = XmlWriter.Create(Console.Out))
    {
        d.WriteTo(xw);
    }

    d.Element("element").SetAttributeValue(xsi + "type", "bar");        
    using (XmlWriter xw = XmlWriter.Create(Console.Out))
    {
        d.WriteTo(xw);
    }

produces this output (whitespace added and XML declarations removed for readability):

<element xmlns:xsi="uriaddress" type="foo" xsi:type="bar" />

<element xmlns:xsi="uriaddress" type="baz" xsi:type="bar" />

<element xmlns:xsi="uriaddress" type="baz" xsi:type="bat" />

If you're not using XDocument (hard to tell from your original post), this code produces essentially the same result:

    XmlDocument d = new XmlDocument();
    d.LoadXml("<element xmlns:xsi='uriaddress' type='foo' xsi:type='bar'/>");
    Console.WriteLine(d.OuterXml);

    d.DocumentElement.SetAttribute("type", "baz");
    Console.WriteLine(d.OuterXml);

    d.DocumentElement.SetAttribute("type", "uriaddress", "bat");
    Console.WriteLine(d.OuterXml);
Robert Rossney
Robert,Thanks you for your help.I did it slightly different and it worked ok. Basically instead of using SetAttribute directly, I created first the attribute as a separate object, then I appended it to the list of attributes. I got the idea from the code you posted, for which I thank you again.Mike