Search code examples
.netxelement

Modify XElement to have different content


I have an XElement which it's output is

<Email>address@email.com</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"/>


Solution

  • 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>