【问题标题】:How can I write xml with a namespace and prefix with XElement?如何使用命名空间和 XElement 前缀编写 xml?
【发布时间】:2010-11-23 05:40:45
【问题描述】:

这可能是一个 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>

如果我能把它写下来,我就能解决剩下的问题。

理想情况下,我想在 c# 中使用 LINQ to XML(XElement、XNamespace 等),但如果使用 XmlDocuments 和 XmlElements 可以更轻松/更好地实现这一点,我会这样做。

谢谢!!!

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    这是一个创建您想要的输出的小例子:

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

    【讨论】:

    • 您不需要在其中使用冒号吗?另外,XNamespace.Xmlns 不输出http://www.w3.org/2000/xmlns/
    • @BrainStorm.exe 否。正如最初的回答,代码按预期工作。当 XNamespace 与字符串一起添加时,会自动添加冒号。这不是必须手动执行的操作。
    【解决方案2】:

    试试这个代码:

    string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
    string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:
        XNamespace ci = "http://somewhere.com";
        XNamespace ca = "http://somewhereelse.com";
        XElement root = new XElement(aw + "root",
            new XAttribute(XNamespace.Xmlns + "ci", "http://somewhere.com"),
            new XAttribute(XNamespace.Xmlns + "ca", "http://somewhereelse.com"),
            new XElement(ci + "field1", "test"),
            new XElement(ca + "field2", "another test")
        );
        Console.WriteLine(root);
        

        这应该输出

        <root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
            <ci:field1>test</ci:field1>
            <ca:field2>another test</ca:field2>
        </root>
        

        【讨论】:

          【解决方案5】:

          对于 XmlDocument 也是类似的:

          XmlAttribute attribute1 = sessionXml.CreateAttribute("s", "Attribute1", namespaceURI);
          XmlAttribute attribute2 = sessionXml.CreateAttribute("s", "Attribute2", namespaceURI);
          XmlAttribute attribute3 = sessionXml.CreateAttribute("s", "Attribute3", namespaceURI);
          XmlAttribute attribute4 = sessionXml.CreateAttribute("s", "Attribute4", namespaceURI);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-21
            • 2012-05-27
            相关资源
            最近更新 更多