Home  >  Article  >  Backend Development  >  How does Linq in Xml traverse stored data?

How does Linq in Xml traverse stored data?

PHPz
PHPzOriginal
2017-04-23 16:40:571941browse

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()
    {
        List iTestResultXml=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 9ca8bcd8dc9da41be539812c43422c59 tag and store them in a list iTestResultXml.

In the testResult.xml file, we see that the 9ca8bcd8dc9da41be539812c43422c59 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 iXmlID = 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 9ca8bcd8dc9da41be539812c43422c59 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!

Statement:
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