简体   繁体   中英

C# XNode add a NameSpace

I have a xNode made by JSON.

C# code:

Class class = new Class();
class.ComboBoxChecked = Class.ComboBoxChecked;
class.RadioButtonChecked = Class.RadioButtonChecked;
string test = JsonConvert.SerializeObject(class);
XNode node = JsonConvert.DeserializeXNode(test, "Root");

XML:

<Root>
  <RadioButtonChecked>1</RadioButtonChecked>
  <ComboBoxChecked>5</ComboBoxChecked>
</Root>

My goal is to add a Namespace to it. How can i achieve this?

You can add namespaces at root level this way:

XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("example", "http://www.w3.org");

    using (var ms = new MemoryStream())
    {
        using (TextWriter writer = new StreamWriter(ms))
        {
            var xmlSerializer = new XmlSerializer(typeof(MyClass));
            xmlSerializer.Serialize(writer, myClassInstance, ns);
            XNode node = XElement.Parse(Encoding.ASCII.GetString(ms.ToArray()));
        }
    }

If you need namespaces in it's children, you can edit your class using the IXmlSerializable interface, here's an Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM