使用XDocument生成具有多个名称空间的XML [英] Generate XML with multiple namespaces using XDocument

查看:61
本文介绍了使用XDocument生成具有多个名称空间的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"/>

尝试像这样使用XDocument生成XML

Try to generate the XML using XDocument like this

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.

Additional information: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

推荐答案

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

To add namespace declaration you can use XNamespace.Xmlns, and to reference the predefined namespace prefix xml use XNamespace.Xml, for example :

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>

这篇关于使用XDocument生成具有多个名称空间的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆