3

I am creating xml in C#, and want to add Namespace and Declaration . My xml as below:

XNamespace ns = "http://ab.com//abc";

XDocument myXML = new XDocument(
    new XDeclaration("1.0","utf-8","yes"),
    new XElement(ns + "Root",
        new XElement("abc","1")))

This will add xmlns="" at both Root level and child element abc level as well.

<Root xmlns="http://ab.com/ab">
    <abc xmlns=""></abc>
</Root>

But I want it in only Root level not in child level like below:

<Root xmlns="http://ab.com/ab">
    <abc></abc>
</Root>

and how to add Declaration at Top, my code not showing Declaration after run.

Please help me to get the complete xml as

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Root xmlns="http://ab.com/ab">
    <abc></abc>
</Root>
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
user1893874
  • 823
  • 4
  • 15
  • 38

2 Answers2

2

You need to use the same namespace in your child elements:

XDocument myXML = new XDocument(
    new XDeclaration("1.0","utf-8","yes"),
        new XElement(ns + "Root",
            new XElement(ns + "abc", "1")))

If you just use "abc" this will be converted to an XName with no Namespace. This then results in an xmlns="" attribute being added so the fully qualified element name for abc would be resolved as such.

By setting the name to ns + "abc" no xmlns attribute will be added when converted to string as the default namespace of http://ab.com/ab is inherited from Root.

If you wanted to simply 'inherit' the namespace then you wouldn't be able to do this in such a fluent way. You'd have create the XName using the namespace of the parent element, for example:

 var root = new XElement(ns + "Root");
 root.Add(new XElement(root.Name.Namespace + "abc", "1"));

Regarding the declaration, XDocument doesn't include this when calling ToString. It will if you use Save to write to a Stream, TextWriter, or if you supply an XmlWriter that doesn't have OmitXmlDeclaration = true in its XmlWriterSettings.

If you wanted to just get the string, this question has an answer with a nifty extension method using a StringWriter.

Community
  • 1
  • 1
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
0

Use the namespace on all elements you create:

XDocument myXML = new XDocument(
                  new XDeclaration("1.0","utf-8","yes"),
                  new XElement(ns + "Root",
                     new XElement(ns + "abc","1")))
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110