How does Linq in Xml traverse stored data?

PHPz
Release: 2017-04-23 16:40:57
Original
2080 people have browsed it

Many times we need to use Xml files, but what is an Xml file?

Let’s use an example to illustrate: testResult.xml file

<?xml version="1.0" encoding="utf-8" ?>
<Columns>
  <column id="序号">
    <name>序号</name>
  </column>
  <column id="检验项目">
    <name>检验项目</name>
  </column>
  <column id="单位">
    <name>单位</name>
  </column>
  <column id="标准要求">
    <name>标准要求</name>
  </column>
  <column id="检验结果">
    <name>检验结果</name>
  </column>
  <column id="结论">
    <name>结论</name>
  </column>
</Columns>
Copy after login

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()
    {
        List<string> iTestResultXml=new List<string>();
        //定义并从xml文件中加载节点(根节点)
        XElement rootNode = XElement.Load(@"..\..\Xml\testResult.xml");   
        //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......)
        IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("column")
                                            select target;
        foreach (XElement node in targetNodes)
        {
            iTestResultXml.Add(node.Value);
        }
    }
Copy after login

In this way we can get all the data in the tag and store them in a list iTestResultXml.

In the testResult.xml file, we see that the tag sets its own id, and this id is not his data, but one of his attributes,

So what if we want to get his attributes instead of the content in his tags?

private void GetTestResultXml()
    {
        List<string> iXmlID = new List<string>();
        //定义并从xml文件中加载节点(根节点)
        XElement rootNode = XElement.Load(@"..\..\Xml\testResult.xml");   
        //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......)
        IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("column")
                                            select target;
        foreach (XElement node in targetNodes)
        {
             iXmlID.Add(node.Attribute("id").Value);   //获取指定属性的方法
        }
    }
Copy after login

In this way we obtain the list iXmlID of the id attribute in the tag.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!