C# XML技术总结之XDocument 和XmlDocument

引言

虽然如今Json在咱们的数据交换中愈来愈成熟,但XML格式的数据还有很重要的地位。html

C#中对XML的处理也不断优化,那么咱们如何选择XML的这几款处理类 XmlReader,XDocument 和XmlDocument了?node

本文就从对照的方式来总结C#中XML的用法。程序员

简介

System.Xml 命名空间(XmlDocument)为处理 XML 提供基于标准的支持。bash

LINQ to XML(XDocument )能够进行如下操做:dom

  • 从文件或流加载 XML。post

  • 将 XML 序列化为文件或流。性能

  • 使用功能构造从头建立 XML 树。优化

  • 使用 LINQ 查询来查询 XML 树。this

  • 操做内存中的 XML 树。google

  • 使用 XSD 验证 XML 树。

  • 组合使用这些功能将 XML 树从一种形状转换为另外一种形状。

 

 

XmlReader,XDocument 和XmlDocument

XDocument 和XmlDocument会把全部的XML全部的节点加载到内存中,而XmlReader则不会把全部节点一块儿加载到内存,而在必定的内存下处理较大的XML。

若是XML文件结构固定,处理比较简单,建议使用XmlReader能够提升程序的性能。

若是XML文件不大或者要作复杂的处理建议使用XDocument。Linq 让程序员省去了不少繁琐冗余的代码,而且兼容设备也比较多,不像XmlDocument在一些设备和系统中不支持。

 

XDocument VS. XmlDocument

 

比较项 XmlDocument(经典DOM API) XDocument (LINQ to XML API)
  须要熟悉DOM知识  
支持的.NetFramework版本 .NET version 1.0 + .NET version 3.5 or later(Linq引入后)
杂项   Unity3D projects for Windows 8.
Xbox 360 and Windows Phone OS 7.0,必须使用XDocument
Namespace  System.Xml System.Xml.Linq
LINQ to XML 不支持 支持
行号信息 不能提供行号信息 经过IXmlLineInfo提供了行号信息
命名空间 支持写 支持元素级写
XPath 不支持 支持, 参考System.Xml.XPath
注释 不支持 支持可扩展的批注集,请参见 LINQ to XML 批注
校验Schema 支持,参考Validate(ValidationEventHandler) 支持 ,参考Validate(XmlSchemaSet, ValidationEventHandler)
加载XML 成员方法加载(须要先new XmlDocument())
静态方法XElement.Load(@"books.xml")

imageimage

 

建立XML文档

使用XmlDocument 的示例

XmlDocument doc = new XmlDocument();
XmlElement name = doc.CreateElement("Name");
name.InnerText = "Patrick Hines";
XmlElement phone1 = doc.CreateElement("Phone");
phone1.SetAttribute("Type", "Home");
phone1.InnerText = "206-555-0144";        
XmlElement phone2 = doc.CreateElement("Phone");
phone2.SetAttribute("Type", "Work");
phone2.InnerText = "425-555-0145";        
XmlElement street1 = doc.CreateElement("Street1");        
street1.InnerText = "123 Main St";
XmlElement city = doc.CreateElement("City");
city.InnerText = "Mercer Island";
XmlElement state = doc.CreateElement("State");
state.InnerText = "WA";
XmlElement postal = doc.CreateElement("Postal");
postal.InnerText = "68042";
XmlElement address = doc.CreateElement("Address");
address.AppendChild(street1);
address.AppendChild(city);
address.AppendChild(state);
address.AppendChild(postal);
XmlElement contact = doc.CreateElement("Contact");
contact.AppendChild(name);
contact.AppendChild(phone1);
contact.AppendChild(phone2);
contact.AppendChild(address);
XmlElement contacts = doc.CreateElement("Contacts");
contacts.AppendChild(contact);
doc.AppendChild(contacts);

使用XDocument 的示例

XElement contacts =
    new XElement("Contacts",
        new XElement("Contact",
            new XElement("Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144", 
                new XAttribute("Type", "Home")),
            new XElement("phone", "425-555-0145",
                new XAttribute("Type", "Work")),
            new XElement("Address",
                new XElement("Street1", "123 Main St"),
                new XElement("City", "Mercer Island"),
                new XElement("State", "WA"),
                new XElement("Postal", "68042")
            )
        )
    );

 

加载XML文件

使用XmlDocument 的示例

XmlDocument booksFromFile = new XmlDocument();
booksFromFile.Load(@"books.xml");

使用XDocument 的示例

XElement booksFromFile = XElement.Load(@"books.xml");

 

命名空间的处理

使用XmlDocument 的示例

public void addXmlns()
{
    string xml = @"<?xml version=""1.0""?>
                    <kml>
                    <Document>
                    <Placemark>
                    </Placemark>
                    </Document>
                    </kml>";

    var xmldoc = new XmlDocument();

    xmldoc.LoadXml(xml);

    xmldoc.DocumentElement.SetAttribute("xmlns", "http://www.opengis.net/kml/2.2");
    xmldoc.DocumentElement.SetAttribute("xmlns:gx", "http://www.google.com/kml/ext/2.2");
    xmldoc.DocumentElement.SetAttribute("xmlns:kml", "http://www.opengis.net/kml/2.2");
    xmldoc.DocumentElement.SetAttribute("xmlns:atom", "http://www.w3.org/2005/Atom");
    xmldoc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

    string message;
    message = xmldoc.InnerXml;

    Console.WriteLine(message); // shows the updated xml  
}

使用XDocument 的示例

示例1,增长namespace

XNamespace ns = "http://somewhere.com";
XElement element = new XElement(ns + "elementName");
// etc
 

示例2,读取含有namespace的文件

string markup = @"
<aw:Root xmlns:aw='http://www.adventure-works.com'>
    <aw:Child1>child one data</aw:Child1>
    <aw:Child2>child two data</aw:Child2>
</aw:Root>";

XmlReader reader = XmlReader.Create(new StringReader(markup));
XElement root = XElement.Load(reader);
XmlNameTable nameTable = reader.NameTable;
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("aw", "http://www.adventure-works.com");
XElement child1 = root.XPathSelectElement("./aw:Child1", namespaceManager);
Console.WriteLine(child1);

 

XDocument 

XDocument  VS. XElement

 

XDocument  XElement
XDocument.Load() 加载整个XML文档  包括根节点 XElement.Load()不会加载XML的根节点

XElement.Load()示例代码

File.WriteAllText("Test.xml", @"<Root>
    <Child1>1</Child1>
    <Child2>2</Child2>
    <Child3>3</Child3>
</Root>");

Console.WriteLine("Querying tree loaded with XElement.Load");
Console.WriteLine("----");
XElement doc = XElement.Load("Test.xml");
IEnumerable<XElement> childList =
    from el in doc.Elements()
    select el;
foreach (XElement e in childList)
    Console.WriteLine(e);

 

XDocument.Load() 示例代码:

File.WriteAllText("Test.xml", @"<Root>
    <Child1>1</Child1>
    <Child2>2</Child2>
    <Child3>3</Child3>
</Root>");

Console.WriteLine("Querying tree loaded with XDocument.Load");
Console.WriteLine("----");
XDocument doc = XDocument.Load("Test.xml");
IEnumerable<XElement> childList =
    from el in doc.Elements()
    select el;
foreach (XElement e in childList)
    Console.WriteLine(e);

 

XPath

XPath的强大之处在于处理元素导航还能够进行计算

示例:

XML文档

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>
 
 

C#处理计算

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");

 

这里只是总结知识点,但具体的关于更多XPath的内容能够移步到XPath 教程

 

XML 批注(注释)

public class MyAnnotation
{
    private string tag;
    public string Tag { get { return tag; } set { tag = value; } }
    public MyAnnotation(string tag)
    {
        this.tag = tag;
    }
}

class Program
{
    static void Main(string[] args)
    {
        XElement root = new XElement("Root", "content");
        root.AddAnnotation(new MyAnnotation("T1"));
        root.AddAnnotation(new MyAnnotation("T2"));
        root.AddAnnotation("abc");
        root.AddAnnotation("def");

        IEnumerable<object> annotationList;
        annotationList = root.Annotations(typeof(MyAnnotation));
        foreach (object ma in annotationList)
            Console.WriteLine(((MyAnnotation)ma).Tag);
        Console.WriteLine("----");

        IEnumerable<object> stringAnnotationList;
        stringAnnotationList = root.Annotations(typeof(string));
        foreach (object str in stringAnnotationList)
            Console.WriteLine((string)str);
    }
}

 

 

总结

如今再写XML相关的程序建议直接使用XDocument,XmlDocument只是主要仍是兼容之前的代码。

另外XPath功能让XDocument如虎添翼,因此你们能够多研究下XPath.

至于XSD和XSL本文不作涉及,又须要的朋友参看参考文献

 

参考

LINQ to XML 与其余 XML 技术

 

1.经过XmlDocument读写Xml文档

2.使用XmlReader读Xml使用XmlWriter写Xml

3.使用Linq to xml存取XML

4.经过XmlScheme定义固定格式xml文档

5.Xml序列化或者反序列化类

6.经过XPath查找Xml节点

7.经过Xslt转化Xml格式

8.XDocument or XmlDocument

9.W3CSchool中提供的XML相关课程

Introduction to XML and XSLT in C# .NET

相关文章
相关标签/搜索