使用XDocument生成具有多个命名空间的XML

3

我有这样的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,不能包含在名称中。

2个回答

5
为了添加命名空间声明,您可以使用 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>

请问如何生成类似于 </stream:stream> 的结束标签,而不是使用 /> - Sowvik Roy

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接