xml解析

来源:互联网 发布:类似processon的软件 编辑:程序博客网 时间:2024/04/27 13:01

引用一下命名空间
using System.Xml.Linq;
using System.Xml.XPath;
事例一
XNamespace aw = "http://hi.csdn.net/liusen5555";
XElement xmlTree1 = new XElement(aw + "Root",
    new XElement(aw + "Child1", 1),
    new XElement(aw + "Child2", 2),
    new XElement(aw + "Child3", 3),
    new XElement(aw + "Child4", 4),
    new XElement(aw + "Child5", 5),
    new XElement(aw + "Child6", 6)
);

XElement xmlTree2 = new XElement(aw + "Root",
    from el in xmlTree1.Elements()
    where((int)el >= 3 && (int)el <= 5)
    select el
);

//遍历解析

 foreach (XElement ele in from el in xmlTree1.Element(aw + "Root") .Elements() select el)
 {
           Console.WriteLine(ele.value); 
}


Console.WriteLine(xmlTree2);

事例二
This one little improvement in System.Xml 2.0 Beta2 is sooo cool anyway: XPathNodeIterator class at last implements IEnumerable! Such unification with .NET iteration model means we can finally iterate over nodes in an XPath selection using standard foreach statement:

XmlDocument doc = new XmlDocument();
doc.Load("orders.xml");
XPathNavigator nav = doc.CreateNavigator();
foreach (XPathNavigator node in nav.Select("/orders/order"))
    Console.WriteLine(node.Value);
Compare this to what we have to write in .NET 1.X:
XmlDocument doc = new XmlDocument();
doc.Load("../../source.xml");
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator ni = nav.Select("/orders/order");
while (ni.MoveNext())     
  Console.WriteLine(ni.Current.Value);
Needless to say - that`s the case when just a dozen lines of code can radically simplify a class`s usage and improve overall developer`s productivity. How come this wasn`t done in .NET 1.1 I have no idea.

And how come the MSDN documentation for the class still doesn`t mention this cool feature - I have no idea either.

原创粉丝点击