[英]How to generate a XML-file with multiple namespaces in root element with XDocument in C#?
[英]Generate XML with multiple namespaces using XDocument
我有这样的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。
要添加命名空间声明可以使用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>
您可以像这样添加名称空间
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.