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>

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. If i dont want to refer namespace in child element then how to implement ?
@user1893874 there's no easy way, I've added a possible option. How you apply this depends on the wider context of your code.
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")))

1 Comment

Thanks for the answers. cant i add namespace only to the Root element ?

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.