Search code examples
c#xelementxnamespace

Creating Xml attribute json:Array using XElement and XNamespace C# classes


I'm trying to build up Xml that looks like the following (taken from another question) but using the XElement/XNamespace classes:

<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
   <name>Alan</name>
   <url>http://www.google.com</url>
   <role json:Array='true'>Admin</role>
</person>

This is so I can serialize using Newtonsoft.Json.JsonConvert.SerializeXmlNode() and maintain correct arrays.

The problem I'm having is creating json:Array='true'.

Other examples show XmlDocument classes or raw creation of Xml string, but is there a way to achieve it using XElement? I've tried several things with XNamespace to attempt to create the "json" prefix without success.


Solution

  • Yes, you can achieve it with XElement. For example:

    XNamespace json = "http://james.newtonking.com/projects/json";
    XDocument xml = new XDocument(new XElement("person",
        new XAttribute(XNamespace.Xmlns + "json", json),
        new XAttribute("id", 1), 
        new XElement("name", "Alan"), 
        new XElement("url", "http://www.google.com"), 
        new XElement("role", new XAttribute(json + "Array", true), "Admin")));
    

    Will produce the following:

    <person xmlns:json="http://james.newtonking.com/projects/json" id="1">
      <name>Alan</name>
      <url>http://www.google.com</url>
      <role json:Array="true">Admin</role>
    </person>