【问题标题】:Generate XML with multiple namespaces using XDocument使用 XDocument 生成具有多个命名空间的 XML
【发布时间】:2014-06-05 05:35:54
【问题描述】:

我有这样的 XML:

<stream:stream to="lap-020.abcd.co.in" from="sourav@lap-020.abcd.co.in" xml:lang="en" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0"/>

尝试像这样使用XDocument 生成 XML

private readonly XNamespace _streamNamespace = "http://etherx.jabber.org/streams";
private readonly XName _stream;

_stream = _streamNamespace + "stream";

XDocument xdoc=new XDocument(
    new XElement(_stream,
        new XAttribute("from", "sourav@lap-020.abcd.co.in"),
        new XAttribute("to","lap-020.abcd.co.in"),
        new XAttribute("xmlns:stream","http://etherx.jabber.org/streams"),
        new XAttribute("version","1.0"),
        new XAttribute("xml:lang","en")
      ));

但我得到一个例外:

附加信息:“:”字符,十六进制值 0x3A,不能包含在名称中。

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    要添加命名空间声明,您可以使用XNamespace.Xmlns,并引用预定义的命名空间前缀xml 使用XNamespace.Xml,例如:

    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>
    

    【讨论】:

    • 你能告诉我如何生成像 这样的结束标签而不是 /> 吗??
    【解决方案2】:

    你可以像

    这样添加命名空间
     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")
    );
    

    此示例产生以下输出:

        <aw:Root xmlns:aw="http://www.adventure-works.com">
      <aw:Child>child content</aw:Child>
    </aw:Root>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多