C#中如何处理XML [英] How to deal with XML in C#

查看:24
本文介绍了C#中如何处理XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 2.0 中处理 XML 文档、XSD 等的最佳方法是什么?

What is the best way to deal with XML documents, XSD etc in C# 2.0?

使用哪些类等.解析和制作 XML 文档等的最佳实践是什么.

Which classes to use etc. What are the best practices of parsing and making XML documents etc.

也欢迎 .Net 3.5 建议.

.Net 3.5 suggestions are also welcome.

推荐答案

在 C# 2.0 中读写的主要方式是通过 XmlDocument 类完成的.您可以通过它接受的 XmlReader 将大部分设置直接加载到 XmlDocument 中.

The primary means of reading and writing in C# 2.0 is done through the XmlDocument class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts.

XmlDocument document = new XmlDocument();
document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>");

从文件加载 XML

XmlDocument document = new XmlDocument();
document.Load(@"C:PathToxmldoc.xml");
// Or using an XmlReader/XmlTextReader
XmlReader reader = XmlReader.Create(@"C:PathToxmldoc.xml");
document.Load(reader);

我发现阅读 XML 文档最简单/最快的方法是使用 XPath.

I find the easiest/fastest way to read an XML document is by using XPath.

XmlDocument document = new XmlDocument();
document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>");

// Select a single node
XmlNode node = document.SelectSingleNode("/People/Person[@Name = 'Nick']");

// Select a list of nodes
XmlNodeList nodes = document.SelectNodes("/People/Person");

如果您需要使用 XSD 文档来验证 XML 文档,您可以使用它.

If you need to work with XSD documents to validate an XML document you can use this.

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd

XmlReader reader = XmlReader.Create(pathToXml, settings);
XmlDocument document = new XmlDocument();

try {
    document.Load(reader);
} catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); }

在每个节点上针对 XSD 验证 XML(更新 1)

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);

XmlReader reader = XmlReader.Create(pathToXml, settings);
while (reader.Read()) { }

private void settings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
    // e.Message, e.Severity (warning, error), e.Error
    // or you can access the reader if you have access to it
    // reader.LineNumber, reader.LinePosition.. etc
}

编写 XML 文档(手动)

XmlWriter writer = XmlWriter.Create(pathToOutput);
writer.WriteStartDocument();
writer.WriteStartElement("People");

writer.WriteStartElement("Person");
writer.WriteAttributeString("Name", "Nick");
writer.WriteEndElement();

writer.WriteStartElement("Person");
writer.WriteStartAttribute("Name");
writer.WriteValue("Nick");
writer.WriteEndAttribute();
writer.WriteEndElement();

writer.WriteEndElement();
writer.WriteEndDocument();

writer.Flush();

(更新 1)

在 .NET 3.5 中,您使用 XDocument 来执行类似的任务.但是,不同之处在于您可以执行 Linq 查询来选择所需的确切数据.通过添加对象初始值设定项,您可以创建一个查询,该查询甚至可以在查询本身中返回您自己定义的对象.

In .NET 3.5, you use XDocument to perform similar tasks. The difference however is you have the advantage of performing Linq Queries to select the exact data you need. With the addition of object initializers you can create a query that even returns objects of your own definition right in the query itself.

    XDocument doc = XDocument.Load(pathToXml);
    List<Person> people = (from xnode in doc.Element("People").Elements("Person")
                       select new Person
                       {
                           Name = xnode.Attribute("Name").Value
                       }).ToList();

(更新 2)

.NET 3.5 中的一个很好的方法是使用 XDocument 创建 XML,如下所示.这使得代码以与所需输出类似的模式出现.

A nice way in .NET 3.5 is to use XDocument to create XML is below. This makes the code appear in a similar pattern to the desired output.

XDocument doc =
        new XDocument(
              new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty),
              new XComment("Xml Document"),
              new XElement("catalog",
                    new XElement("book", new XAttribute("id", "bk001"),
                          new XElement("title", "Book Title")
                    )
              )
        );

创建

<!--Xml Document-->
<catalog>
  <book id="bk001">
    <title>Book Title</title>
  </book>
</catalog>

所有其他方法都失败了,您可以查看这篇 MSDN 文章,其中包含我在此处讨论过的许多示例以及更多示例.http://msdn.microsoft.com/en-us/library/aa468556.aspx

All else fails, you can check out this MSDN article that has many examples that I've discussed here and more. http://msdn.microsoft.com/en-us/library/aa468556.aspx

这篇关于C#中如何处理XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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