Using XNamespace to create nicely formatted XML

早过忘川 提交于 2020-01-13 10:53:07

问题


I want to create a Xml file that looks something like this:

<Root xmlns:ns1="name1" xmlns:ns2="name2">
    <ns1:element1 />
    <ns1:element2 />
    <ns2:element3 />
</Root>

How can I accomplish this using XAttribute, XElement, XNamespace, and XDocument where the namespaces are dynamically added.


回答1:


I assume by "namespaces are dynamically added" you mean the namespace prefix. This generates the document, how close is it to what you meant?

        XNamespace ns1 = "name1", ns2 = "name2";

        XElement elem = new XElement("Root", 
                new XAttribute(XNamespace.Xmlns + "ns1", ns1), 
                new XAttribute(XNamespace.Xmlns + "ns2", ns2),
                new XElement(ns1 + "element1"),
                new XElement(ns1 + "element2"),
                new XElement(ns2 + "element3"));

        elem.Save("example.xml");


来源:https://stackoverflow.com/questions/2572243/using-xnamespace-to-create-nicely-formatted-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!