2

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.

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.