简体   繁体   中英

Generate XML with multiple namespaces using XDocument

I have XML like this:

<stream:stream to="lap-020.abcd.co.in" from="sourav@lap-020.abcd.co.in" xml:lang="en" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0"/>

Try to generate the XML using XDocument like this

private readonly XNamespace _streamNamespace = "http://etherx.jabber.org/streams";
private readonly XName _stream;

_stream = _streamNamespace + "stream";

XDocument xdoc=new XDocument(
    new XElement(_stream,
        new XAttribute("from", "sourav@lap-020.abcd.co.in"),
        new XAttribute("to","lap-020.abcd.co.in"),
        new XAttribute("xmlns:stream","http://etherx.jabber.org/streams"),
        new XAttribute("version","1.0"),
        new XAttribute("xml:lang","en")
      ));

But I get an exception:

Additional information: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

To add namespace declaration you can use XNamespace.Xmlns , and to reference the predefined namespace prefix xml use XNamespace.Xml , for example :

XNamespace stream = "http://etherx.jabber.org/streams";
var result = new XElement(stream + "stream",
                    new XAttribute("from", "sourav@lap-020.abcd.co.in"),
                    new XAttribute("to","lap-020.abcd.co.in"),
                    new XAttribute(XNamespace.Xmlns + "stream", stream),
                    new XAttribute("version","1.0"),
                    new XAttribute(XNamespace.Xml+"lang","en"),
                    String.Empty);
Console.WriteLine(result);
//above prints :
//<stream:stream from="sourav@lap-020.abcd.co.in" to="lap-020.abcd.co.in" 
//               xmlns:stream="http://etherx.jabber.org/streams" version="1.0" 
//               xml:lang="en">
//</stream:stream>

you can add the namespace like

 XElement root = new XElement("{http://www.adventure-works.com}Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XElement("{http://www.adventure-works.com}Child", "child content")
);

This example produces the following output:

    <aw:Root xmlns:aw="http://www.adventure-works.com">
  <aw:Child>child content</aw:Child>
</aw:Root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM