<?xml version="1.0" encoding="utf-8"?> <PathList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Path> <PathName>PM_CableLoss</PathName> <PathID>1</PathID> <AdditionalLoss>0</AdditionalLoss> <Cal_Date>4/7/2010 3:58 PM</Cal_Date> <TesterID>TesterA</TesterID> <CalCable_PathName>CAL_CABLE</CalCable_PathName> <UseCalCable>true</UseCalCable> <DataList> <Data> <Frequency>2412</Frequency> <Value>10.7</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2417</Frequency> <Value>10.7</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2422</Frequency> <Value>10.8</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2427</Frequency> <Value>10.9</Value> <Delta>0.0</Delta> </Data> </DataList> </Path> <Path> <PathName>Test_CableLoss</PathName> <PathID>2</PathID> <AdditionalLoss>0</AdditionalLoss> <Cal_Date>4/7/2010 3:58 PM</Cal_Date> <TesterID>TesterB</TesterID> <CalCable_PathName>CAL_CABLE</CalCable_PathName> <UseCalCable>true</UseCalCable> <DataList> <Data> <Frequency>2412</Frequency> <Value>0</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2417</Frequency> <Value>0</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2422</Frequency> <Value>0</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2427</Frequency> <Value>0</Value> <Delta>0.0</Delta> </Data> <Data> <Frequency>2432</Frequency> <Value>0</Value> <Delta>0.0</Delta> </Data> </DataList> </Path> </PathList>
上面是要操作的XML,下面是我自己的代码。
XmlDocument xml = new XmlDocument(); xml.Load("loss.xml"); XmlNodeList xnl = xml.SelectNodes("/PathList/Path/DataList/Data"); foreach (XmlNode x in xnl) { string firstName = x["Frequency"].InnerText; string lastName = x["Value"].InnerText; Console.WriteLine("{0}\t {1}", firstName, lastName); }
问题是我不想一次遍历出所有结果,我想按 <PathName>PM_CableLoss</PathName>这个字段分别遍历,知道有好的方法,但一直想不出,对Linq to xml也不熟,求大神相助,谢谢!
XDocument linqToXmlDoc = XDocument.Load("loss.xml"); XElement rootNode = linqToXmlDoc.Element("PathList"); IEnumerable<XElement> nodes = rootNode.Elements("Path"); var nodesByPathName = nodes.Where(x => x.Element("PathName").Value =="PM_CableLoss"); var nodesList = nodesByPathName.ToList();
谢谢解答! 已经设置为最佳答案!
虽然后面的用XElement遍历方式还没有搞定,但是把前单部分的整体已经提取到了,我自己再研究一下!
@TabZ: 可以转实体,xml转实体(反序列化),面向对象。
@~扎克伯格: 谢谢!看来我得花点时间深入一下XML了!
XElement root = XElement.Load(XmlFile);
var paremeters =from c in root.Descendants("PathName")
select c).ToArray();
感谢回复!不过有点小问题
1. ToArray()方法不存在。
2. 我不是要提取PathName本身,我用它只是用来分组,最终还是要得到对应的Frequency,Value的遍历结果。
@TabZ:
查一下这个方法Descendants怎么用的就知道了