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

Sow*_*Roy 3 c# xml linq-to-xml

我有这样的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"/>
Run Code Online (Sandbox Code Playgroud)

尝试使用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")
      ));
Run Code Online (Sandbox Code Playgroud)

但我得到一个例外:

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

har*_*r07 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>
Run Code Online (Sandbox Code Playgroud)