如何使用命名空间和XElement前缀编写xml?

Chr*_*way 22 c# xml linq-to-xml

这可能是一个初学者xml问题,但是如何生成如下所示的xml文档呢?

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
    <ci:field1>test</ci:field1>
    <ca:field2>another test</ca:field2>
</root>
Run Code Online (Sandbox Code Playgroud)

如果我可以写这个,我可以解决我的其余问题.

理想情况下,我想使用c#使用LINQ to XML(XElement,XNamespace等),但如果使用XmlDocuments和XmlElements可以更容易/更好地实现这一点,我会继续使用它.

谢谢!!!

And*_*are 44

这是一个创建所需输出的小例子:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        XNamespace ci = "http://somewhere.com";
        XNamespace ca = "http://somewhereelse.com";

        XElement element = new XElement("root",
            new XAttribute(XNamespace.Xmlns + "ci", ci),
            new XAttribute(XNamespace.Xmlns + "ca", ca),
                new XElement(ci + "field1", "test"),
                new XElement(ca + "field2", "another test"));
    }
}
Run Code Online (Sandbox Code Playgroud)