-->

How do I Skip XML Reader by reading empty attribut

2019-08-19 05:06发布

问题:

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();
        }
    }
}