我有这样的 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")
));
但我得到一个异常(exception):
Additional information: The ':' character, hexadecimal value 0x3A, cannot be included in a name.
最佳答案
要添加命名空间声明,您可以使用 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>
关于c# - 使用 XDocument 生成具有多个命名空间的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40271126/