Many times we need to use Xml files, but what is an Xml file?
Let’s use an example to illustrate: testResult.xml file
序号 检验项目 单位 标准要求 检验结果 结论
The above is an Xml file. We know that Xml files are used to store data , so how do we traverse this data?
In fact, the simplest way is to use Linq:
private void GetTestResultXml() { ListiTestResultXml=new List (); //定义并从xml文件中加载节点(根节点) XElement rootNode = XElement.Load(@"..\..\Xml\testResult.xml"); //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......) IEnumerable targetNodes = from target in rootNode.Descendants("column") select target; foreach (XElement node in targetNodes) { iTestResultXml.Add(node.Value); } }
In this way we can get all the data in the
In the testResult.xml file, we see that the
So what if we want to get his attributes instead of the content in his tags?
private void GetTestResultXml() { ListiXmlID = new List (); //定义并从xml文件中加载节点(根节点) XElement rootNode = XElement.Load(@"..\..\Xml\testResult.xml"); //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......) IEnumerable targetNodes = from target in rootNode.Descendants("column") select target; foreach (XElement node in targetNodes) { iXmlID.Add(node.Attribute("id").Value); //获取指定属性的方法 } }
In this way we obtain the list iXmlID of the id attribute in the
The above is the detailed content of How does Linq in Xml traverse stored data?. For more information, please follow other related articles on the PHP Chinese website!