使用属性编写xmlns元素

时间:2013-06-12 23:52:47

标签: xml vb.net xmlwriter

我使用XmlWriter生成XML文件。我试图复制一个旧的XML文件,我想创建一个看起来像的条目;

<Return xmlns="http://address/here" appName="Data Return - Collection Tool" appVer="1.1.0">

我的代码如下:

        writer.WriteStartElement("Return", "http://address/here")
        writer.WriteAttributeString("appName", "Data Return - Collection Tool")
        writer.WriteAttributeString("appVer", "1.1.0")

这是以错误的顺序生成属性,即

<Return appName="Data Return - Collection Tool" appVer="1.1.0" xmlns="http://address/here">

我怎样才能让这些按照我想要的顺序出现。 请帮忙。

1 个答案:

答案 0 :(得分:3)

XmlWriter允许您在需要时编写xmlns属性,如果该值与WriteStartElement中指定的值相同:

void Main()
{
    StringWriter stringWriter = new StringWriter();
    using(XmlWriter writer = XmlWriter.Create(stringWriter))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("Return", "http://address/here");
        writer.WriteAttributeString("xmlns", "http://address/here");
        writer.WriteAttributeString("appName", "Data Return - Collection Tool");
        writer.WriteAttributeString("appVer", "1.1.0");
        writer.WriteEndElement();
        writer.WriteEndDocument();
    }

    Console.WriteLine(stringWriter.ToString());
}

输出:

<Return xmlns="http://address/here" appName="Data Return - Collection Tool" appVer="1.1.0" />