如何使用C#中的WriteStartDocument WriteStartElement WriteAttributeString格式化XML?

时间:2014-12-07 19:39:29

标签: c# xml xmlwriter

我希望XML的格式如下:

<?xml version="1.0" encoding="UTF-8"?>
<ftc:A xmlns="urn:oecd:ties:stfatypes:v1" xmlns:ftc="urn:oecd:ties:a:v1" xmlns:xsi="http://www.a.com/2001/XMLSchema-instance" version="1.1" xsi:schemaLocation="urn:oecd:ties:a:v1 aXML_v1.1.xsd">
    <ftc:b>
        <z issuedBy = "s">1</z>
        <x>CO</x>
    </ftc:b>
</ftc:A>

我忘记了发布的属性, 我在编写方法的属性时遇到了麻烦:

writer.WriteStartDocument ();
writer.WriteStartElement ();
writer.WriteAttributeString ();
writer.WriteElementString ();

我只需要C#中的例子,请:)

1 个答案:

答案 0 :(得分:1)

就像t3chb0t所说的那样,像XDocument这样的新类会让这更容易。但假设您需要使用XmlWriter,请按照以下步骤操作:

const string rootNamespace = "urn:oecd:ties:stfatypes:v1";
const string ftcNamespace = "urn:oecd:ties:a:v1";
const string xsiNamespace = "http://www.a.com/2001/XMLSchema-instance";

var settings = new XmlWriterSettings
{
    Indent = true,
};

var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb, settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("ftc", "A", ftcNamespace);
    writer.WriteAttributeString("xmlns", "", null, rootNamespace);
    writer.WriteAttributeString("xmlns", "ftc", null, ftcNamespace);
    writer.WriteAttributeString("xmlns", "xsi", null, xsiNamespace);
    writer.WriteAttributeString("version", "1.1");
    writer.WriteAttributeString("schemaLocation", xsiNamespace, "urn:oecd:ties:a:v1 aXML_v1.1.xsd");
    writer.WriteStartElement("b", ftcNamespace);
    writer.WriteElementString("z", rootNamespace, "1");
    writer.WriteElementString("x", rootNamespace, "CO");
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndDocument();
}