C# XmlDocument读写xml

776 阅读2分钟

这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战

C# 的XmlDocument类是 XML 文档的内存中表示形式。 它实现 W3C 级别1核心和核心 DOM 级别2。

XML 文档对象模型 (DOM)

XML 文档对象模型 (DOM) 类是 XML 文档的内存中表示形式。 DOM 使您能够以编程方式读取、处理和修改 XML 文档。 虽然 XmlReader 类也读取 XML,但它提供的是非缓存、仅正向的只读访问。 也就是说,使用 XmlReader 无法编辑属性值或元素内容,也无法插入和删除节点。 编辑是 DOM 的主要功能。 XML 数据在内存中表示是常见的结构化方法,尽管实际的 XML 数据在文件中时或从另一个对象传入时以线性方式存储。 以下是 XML 数据。

<?xml version="1.0"?>
<books>
    <book>
        <author>Carson</author>
        <price format="dollar">31.95</price>
        <pubdate>05/01/2001</pubdate>
    </book>
    <pubinfo>
        <publisher>MSPress</publisher>
        <state>WA</state>
    </pubinfo>
</books>

XML 数据读入 DOM 结构中时如何构造内存。

image.png

使用XmlDocument构造XML

如上文档我们通过XmlDocument类来构建。

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
XmlElement xmlRootNode = xmlDoc.CreateElement("books");

XmlElement bookNode = xmlDoc.CreateElement("book");
XmlElement authorNode = xmlDoc.CreateElement("author");
authorNode.InnerText="Carson";
bookNode.AppendChild(authorNode);

XmlElement authorNode = xmlDoc.CreateElement("author");
authorNode.InnerText="Carson";
bookNode.AppendChild(authorNode);

XmlElement priceNode = xmlDoc.CreateElement("price");
authorNode.InnerText="31.95";
authorNode.SetAttribute("format","dollar");
bookNode.AppendChild(priceNode);

XmlElement pubdateNode = xmlDoc.CreateElement("pubdate");
pubdateNode.InnerText="05/01/2001";
bookNode.AppendChild(pubdateNode);
xmlRootNode.AppendChild(bookNode);


XmlElement pubinfoNode = xmlDoc.CreateElement("pubinfo");

XmlElement publisherNode = xmlDoc.CreateElement("publisher");
publisherNode.InnerText="MSPress";
pubinfoNode.AppendChild(publisherNode);

XmlElement stateNode = xmlDoc.CreateElement("state");
stateNode.InnerText="WA";
pubinfoNode.AppendChild(stateNode);
xmlRootNode.AppendChild(pubinfoNode);

使用XmlDocument初始化文档,然后CreateXmlDeclaration() 设置xml头。最后用AppendChild的方式将节点组织到xml结构中。

存储和获取xml文本

xmlDoc.Save(path) 方法传入要存入的文件路径Path就能直接将xml的文档保存到文件。如果要想直接获取XML 还要使用XmlWriter 将xml写入后获取文本。

XmlWriter xmlWriter = null;

XmlWriterSettings settings = new XmlWriterSettings();
//要求缩进
settings.Indent = true;
//设置encoding utf-8,默认将输出utf-16
settings.Encoding = new UTF8Encoding(false);
//设置换行符
settings.NewLineChars = Environment.NewLine;

MemoryStream ms = new MemoryStream();
try
{
    xmlWriter = XmlWriter.Create(ms, settings);
    xmlWriter.WriteStartDocument();
    xmlDoc.WriteTo(xmlWriter);
}
finally
{
    if (xmlWriter != null)
        xmlWriter.Close();
    ms.Close();
}
string xmlStr=Encoding.UTF8.GetString(ms.ToArray());

这样我们就能获取到xml的文本了,可以直接存入数据库字段。还有其它的方式读写xml,比如直接使用XmlWriter。下次在讲XmlWriter。