开发者

Filtering out empty tags in XML with C#

开发者 https://www.devze.com 2023-03-11 16:07 出处:网络
So I am using this code to parse a gigantic (80,000 line) XML document. However when it was handed to me it added unnessecary rows due to parent nodes(which was fixed by the if statement in the code),

So I am using this code to parse a gigantic (80,000 line) XML document. However when it was handed to me it added unnessecary rows due to parent nodes(which was fixed by the if statement in the code), and now it is doubling up on empty nodes.

Whenever I hit an empty node it will double up on the node before it... for example here is a peice of the xml:

<edit>
    <who>Jim Johnson(Jim.m.Johnson@google.com)</who>
    <when>2010-08-18T12:14:33.613Z</when>
    <description></description>
</edit>

And the data feed I am getting ends up looking like:

who                Jim Johnson
when               8/18/2010
description        8/18/2010
开发者_Go百科

Anyone have a good idea as to how to trim off those empty tags? Here is a peice of the code that is generating this table.

using (XmlReader reader = XmlReader.Create(new StringReader(
{
    // Parse the file and display each of the nodes.
    while (reader.Read())
    {
        switch (reader.NodeType)
        {
            case XmlNodeType.Element:
                elementName = reader.Name;
                switch (elementName)
                {
                    //display my title stuff
                }
                break;
            case XmlNodeType.Text:
                elementText = reader.Value;
                break;
            case XmlNodeType.XmlDeclaration:
            case XmlNodeType.ProcessingInstruction:
                break;
            case XmlNodeType.Comment:
                break;
            case XmlNodeType.EndElement:
                if (elementName == reader.Name)
                {
                    contractRowArray1[0] = elementName;
                    contractRowArray1[1] = elementText;
                    contractRow = contractTable.NewRow();
                    contractRow.ItemArray = contractRowArray1;
                    contractTable.Rows.Add(contractRow);
                }
                break;
        }
    }
}


Does this work?

case XmlNodeType.Element:
    elementName = reader.Name;
    elementText = null;                  // ADDED
    switch (elementName)
    {
        //display my title stuff
    }
    break;

...

case XmlNodeType.EndElement:
    if (elementName == reader.Name && elementText != null)       // MODIFIED
    {
        contractRowArray1[0] = elementName;
        contractRowArray1[1] = elementText;
        contractRow = contractTable.NewRow();
        contractRow.ItemArray = contractRowArray1;
        contractTable.Rows.Add(contractRow);
    }
    break;
0

精彩评论

暂无评论...
验证码 换一张
取 消