Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify XElement to have different content

Tags:

.net

xelement

I have an XElement which it's output is

<Email>[email protected]</Email>

. Base on some criteria I will possibly need to remove the email address and set it to null. I know I can yous set element.Value =""; but that will not do what I want. I want to modify it so the output will become:

<Email xsi:nil=\"true\" />

I don't want to create a brand new node because this is a referenced node within a document. and i want to keep the node where it is within the document. I tried

emailItem.Add(new XAttribute("xsi:nil", "true"));

but I received the following exception

The ':' character, hexadecimal value 0x3A, cannot be included in a name. The following changes create the node almost correctly:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";                                    
emailItem.Add(new XAttribute(xsi + "nil", true));
emailItem.Value =""; //How do I set to Null?

I end up with <Email xsi:nil="true"></Email> instead <Email xsi:nil="true"/>

like image 704
greektreat Avatar asked May 09 '12 18:05

greektreat


2 Answers

Yes, you need to specify the XName differently; you can't just create an XName in a namespace like that.

I suspect you want this:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
emailItem.Document.Root.Add(new XAttribute(XNamespace.Xmlns + "xsi",
                            xsi.ToString()));
emailItem.Add(new XAttribute(xsi + "nil", true);

Complete example:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = new XDocument(new XElement("root"));
        XElement element = new XElement("email");
        doc.Root.Add(element);
        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
        element.Document.Root.Add(
            new XAttribute(XNamespace.Xmlns + "xsi", xsi.ToString()));
        element.Add(new XAttribute(xsi + "nil", true));

        Console.WriteLine(doc);
    }
}

Output:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <email xsi:nil="true" />
</root>
like image 95
Jon Skeet Avatar answered Oct 18 '22 07:10

Jon Skeet


You probably want the xsi to map to the XML schema instance namespace, so in this case you need to specify that:

    XElement root = new XElement("root");
    root.Add(new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    XElement emailItem = XElement.Parse(@"<Email>[email protected]</Email>");
    root.Add(emailItem);
    emailItem.Add(new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), "true"));
    Console.WriteLine(root);

Notice that you don't need the root element (I just added it so that the namespace declaration doesn't go to the Email element itself).

like image 1
carlosfigueira Avatar answered Oct 18 '22 08:10

carlosfigueira