如何使用C#中的XmlWriter类生成以下Xml

本文关键字:Xml 何使用 中的 XmlWriter | 更新日期: 2023-09-27 18:26:30

我想使用C#中的XmlWriter类生成以下格式的XML:

<?xml version="1.0" ?>
<root>
 <data>
  <entry Attrib1="" Attrib2="91.3467" Attrib3="95.3052" Attrib4="6.4722" />
  <entry Attrib1="" Attrib2="91.3467" Attrib3="95.3052" Attrib4="6.4722" />
 </data>
</root>

我对XmlWriter类和C#都很陌生,我尝试过用上面的格式编写生成文件的代码,但尝试没有成功

var xmlWriter = XmlWriter.Create(filename);
    xmlWriter.WriteStartDocument();
    xmlWriter.WriteStartElement("data");
    xmlWriter.WriteStartElement("entry");
    xmlWriter.WriteAttributeString("attrib1", "value1");
    xmlWriter.WriteAttributeString("attrib2", "value2");
    xmlWriter.Close();

此外,属性的名称可能包括非法的XML字符,这就是我阅读XMLWriter的原因,因为它似乎从属性的名称中删除了这些非法字符——例如,当写入到生成的XML时,像"这是属性1"这样的名称应该减少为像"this_is_attribute_1"这样的内容,我如何使用XmlWriter生成这样的XML。简而言之,生成的一行XML类似于以下

<entry P_B_Pe="" P_E_Pe="91.3467" Custom_Price="95.3052" C_Yield="6.4722" Average_Life="" />

如何使用C#中的XmlWriter类生成以下Xml

你几乎得到了…

var xmlWriter = XmlWriter.Create(filename);
    xmlWriter.WriteStartDocument();
        xmlWriter.WriteStartElement("root");
            xmlWriter.WriteStartElement("data");
                xmlWriter.WriteStartElement("entry");
                    xmlWriter.WriteAttributeString("attrib1", "value1");
                    xmlWriter.WriteAttributeString("attrib2", "value2");
                xmlWriter.WriteEndElement(); // entry
                xmlWriter.WriteStartElement("entry");
                    xmlWriter.WriteAttributeString("attrib1", "value1");
                    xmlWriter.WriteAttributeString("attrib2", "value2");
                xmlWriter.WriteEndElement(); // entry
            xmlWriter.WriteEndElement(); // data
        xmlWriter.WriteEndElement(); // root
    xmlWriter.WriteEndDocument();
xmlWriter.Close();

默认情况下,XmlWriter将对原始数据或属性值中通常无效的字符进行编码,使它们在使用读取器解码XML时返回,但属性和元素名称必须仍然有效。如果你想以某种不同于此的特殊方式处理无效字符,你需要根据你想要建立的任何规则自己处理,比如:

xmlWriter.WriteAttributeString(MyXmlExtensions.EncodeXmlAttributeName("this is normally an invalid attribute name"), "value1");
class MyXmlExtensions
{
    public string EncodeXmlAttributeName(string decoded)
    {
        // not that you'll likely need to enhance this with whatever rules you want but haven't specified
        return decoded.Replace(" ", "_");
    }
    public string DecodeXmlAttributeName(string encoded)
    {
        // not that you'll likely need to enhance this with whatever rules you want but haven't specified
        return encoded.Replace("_", " ");
    }
}

如果您希望输出看起来漂亮(选项卡、多行等),还需要在对XmlWriter.Create的调用中使用XmlWriterSettings

尝试XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:'temp'test.xml";
        static void Main(string[] args)
        {
            StreamWriter sWriter = new StreamWriter(FILENAME);
            XmlTextWriter writer = new XmlTextWriter(sWriter);
            writer.WriteStartDocument();
            writer.WriteStartElement("root");
            writer.WriteStartElement("data");
            double?[] attributes = new double?[] { null, 91.3467, 95.3052, 6.4722 };
            XElement entry = new XElement("entry");
            int index = 1;
            foreach (double? attribute in attributes)
            {
                if (attribute == null)
                {
                    entry.Add(new XAttribute("Attrib" + index++.ToString(), ""));
                }
                else
                {
                    entry.Add(new XAttribute("Attrib" + index++.ToString(), attribute));
                }
            }
            writer.WriteRaw(entry.ToString());
            writer.WriteRaw(entry.ToString());
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();

        }
    }
}
​

做没有任何xml linq然后

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:'temp'test.xml";
        static void Main(string[] args)
        {
            StreamWriter sWriter = new StreamWriter(FILENAME);
            XmlTextWriter writer = new XmlTextWriter(sWriter);
            writer.WriteStartDocument();
            writer.WriteStartElement("root");
            writer.WriteStartElement("data");
            writer.WriteStartElement("entry");
            double?[] attributes = new double?[] { null, 91.3467, 95.3052, 6.4722 };
            int index = 1;
            foreach (double? attribute in attributes)
            {
                writer.WriteStartAttribute("Attrib" + index++.ToString());
                if (attribute == null)
                {
                    writer.WriteValue("");
                }
                else
                {
                    writer.WriteValue(attribute);
                } 
                writer.WriteEndAttribute();
            }
            writer.WriteEndElement();
            writer.WriteStartElement("entry");
            attributes = new double?[] { null, 91.3467, 95.3052, 6.4722 };
            index = 1;
            foreach (double? attribute in attributes)
            {
                writer.WriteStartAttribute("Attrib" + index++.ToString());
                if (attribute == null)
                {
                    writer.WriteValue("");
                }
                else
                {
                    writer.WriteValue(attribute);
                }
                writer.WriteEndAttribute();
            }
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();

        }
    }
}
​

使用对象序列化,就不必有对象到结构的映射代码

using System.Xml.Serialization;
...
[XmlRoot("root")]
public class Example {
    [XmlElement("data")]
    public Entries Entries { get; set; }
}
public class Entries : List<List<string>>, IXmlSerializable {
    public List<string> Attribs { get; set; }
    public System.Xml.Schema.XmlSchema GetSchema() { return null; }
    public void ReadXml(System.Xml.XmlReader reader) { reader.MoveToContent(); }
    public void WriteXml(System.Xml.XmlWriter writer) {
        foreach (var entry in this) {
            writer.WriteStartElement("entry", "");
            var label = 1;
            foreach (var attrib in entry) {
                writer.WriteAttributeString(string.Format("Attrib{0}", label), attrib);
                label++;
            }
            writer.WriteEndElement();
        }
    }
}
...
var xml = new XmlSerializer(typeof(Example), "");
xml.Serialize(stream, example);