Generate XML with multiple namespaces using XDocument

前端 未结 2 1792
礼貌的吻别
礼貌的吻别 2021-01-14 13:47

I have XML like this:



        
相关标签:
2条回答
  • 2021-01-14 14:41

    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>
    
    0 讨论(0)
  • 2021-01-14 14:45

    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>
    
    0 讨论(0)
提交回复
热议问题