7

I'm creating an XML document using System.XML in C#.

I'm almost done, but I need to add some similar to the following to the top of my document:

<ABC xmlns="http://www.acme.com/ABC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" fileName="acmeth.xml" date="2011-09-16T10:43:54.91+01:00" origin="TEST" ref="XX_88888">

I need to add this just below where I have:

<?xml version="1.0" encoding="UTF-8"?>

I create this using the following code:

XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };

After this I go on to create my XML document, which is finished now but I need to add this in-between.

Thanks

John

2
  • Maybe I'm missing something, but what is the question? Commented Sep 29, 2011 at 18:31
  • Please show your current code, at least the code to create the root element. Commented Sep 29, 2011 at 18:31

2 Answers 2

22

I think this is what you're after:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XNamespace ns = "http://www.acme.com/ABC";
        DateTimeOffset date = new DateTimeOffset(2011, 9, 16, 10, 43, 54, 91,
                                                 TimeSpan.FromHours(1));
        XDocument doc = new XDocument(
            new XElement(ns + "ABC",
                         new XAttribute("xmlns", ns.NamespaceName),
                         new XAttribute(XNamespace.Xmlns + "xsi",
                              "http://www.w3.org/2001/XMLSchema-instance"),
                         new XAttribute("fileName", "acmeth.xml"),
                         new XAttribute("date", date),
                         new XAttribute("origin", "TEST"),
                         new XAttribute("ref", "XX_88888")));

        Console.WriteLine(doc); 
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is new XAttribute("xmlns", ns.NamespaceName) necessary? You're already setting the element's default namespace in the line above, no?
@spender: Well, we're setting the element's namespace - but we're not explicitly setting the default namespace. It seems to work without it in this case, but personally I'd rather be explicit.
8

You can add namespace declarations to the root element of an XmlDocument like this:

document.DocumentElement.SetAttribute("xmlns", "http://default-namespace");
document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");

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.