Modify XElement to have different content

I have an XElement that it outputs

<Email>address@email.com</Email>

. Based on some criteria, I may need to remove the email address and set it to null. I know that I can set set.Value = ""; but it will not do what I want. I want to change it so that the result is as follows:

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

I do not want to create a new node, because this is the node link in the document. and I want to keep the node where it is inside the document. I tried

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

but I got the following exception

The character ':', the hexadecimal value 0x3A, cannot be included in the 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?

In the end, I get <Email xsi:nil="true"></Email> <Email xsi:nil="true"/>

+5
source share
2 answers

, XName -; XName , .

, :

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);

:

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);
    }
}

:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <email xsi:nil="true" />
</root>
+8

, , xsi XML-, , :

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

, ( , Email).

+1

All Articles