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

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

问题描述

那么,什么是处理XML文档,XSD和所有的东西在C#2.0的最佳方法是什么?用什么类等什么样的事情是分析的最佳实践,使XML文档等。

So what is the best way to deal with XML documents, XSD and all that stuff in C# 2.0? What classes to use etc. Like 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:\Path\To\xmldoc.xml");
// Or using an XmlReader/XmlTextReader
XmlReader reader = XmlReader.Create(@"C:\Path\To\xmldoc.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); }

验证XML对XSD在每个节点(更新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();

(更新一)

(UPDATE 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)

(UPDATE 2)

在.NET 3.5中一个很好的方法是使用的XDocument创建XML如下。这使得code中出现类似的模式,以所希望的输出。

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

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

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