How do I Skip XML Reader by reading empty attribute node?

眉间皱痕 提交于 2019-12-25 02:28:39

问题


I want to skip empty id parent node and move to not empty id parent node in this kind of XML document.Currently my program using XmlTextReader to read and process this XML. But sometime record id can be empty and that time I want to skip this record parent node and reader should move to next node without reading that empty id parent node. Guys do you have any idea to do that ? Please help me !!!

`<record id="">
  <record><data></data></record>
  <record><data></data></record>
 </record>
 <record id="###">
  <record><data></data></record>
  <record><data></data></record>
 </record>

`


回答1:


I like using a combination of XmlReader and Xml Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            while (!reader.EOF)
            {
                if (reader.Name != "record")
                {
                    reader.ReadToFollowing("record");
                }
                if (!reader.EOF)
                {
                    XElement record = (XElement)XElement.ReadFrom(reader);
                    string id = (string)record.Attribute("id");
                    if (id.Length > 0)
                    {
                        Console.WriteLine("id = '{0}'", id.ToString());
                    }
                }
            }
            Console.ReadLine();
        }
    }
}


来源:https://stackoverflow.com/questions/49189562/how-do-i-skip-xml-reader-by-reading-empty-attribute-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!