开发者

Using XNamespace to create nicely formatted XML

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

<Root xmlns:ns1="name1" xmlns:ns2="name2">

  &n开发者_如何学Gobsp; <ns1:element1 />

    <ns1:element2 />

    <ns2:element3 />

</Root>

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


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜