没有返回字符时,XMLReader失败

时间:2010-11-23 18:48:28

标签: .net xmlreader

我正在使用XML阅读器类,我已经做了下面的例子。

        XmlReader xmlreader = XmlReader.Create("http://adomain/companies.xml");

        while (xmlreader.ReadToFollowing("company"))
        {
            Console.WriteLine("Company {0}",xmlreader.ReadElementContentAsString());

            if (xmlreader.ReadToFollowing("employees"))
            {
                Console.WriteLine("Employees{0}", xmlreader.ReadElementContentAsString());
            }
            Console.WriteLine();
        }

当XML具有回车结果时,代码可以正常工作,如下所示

公司网络蜘蛛公司 Employees20

Google公司 Employees20000

公司Simons Gremlin网页设计 雇员1

使用像这样的xml

<?xml version =“1.0”encoding =“UTF-8”?>
<公司>
< company> Web Spiders Co< / company>
<员工> 20℃/雇员>
<公司>谷歌< /公司>
<员工> 20000< /雇员>
< company> Simons Gremlin Web Design< / company>
<员工→1< /雇员>
< /公司>

然而,当我从XML

中删除换行符时

即。 <?xml version =“1.0”encoding =“UTF-8”?> <公司> < company> Web Spiders Co< / company> <员工> 20℃/雇员> <公司>谷歌< /公司> <员工> 20000< /雇员> < company> Simons Gremlin Web Design< / company> <员工→1< /雇员> < /公司>

然后xmlreader开始跳过元素,我的结果集看起来非常不同

e.g。

公司网络蜘蛛公司 Employees20000

我真的不明白为什么会这样,以及为什么XML阅读器会以这种方式运行。

1 个答案:

答案 0 :(得分:2)

这是失败的,因为当您有换行符时,会有一个类型为Whitespace的额外节点,这会使您的逻辑正常工作。如果没有新行和读者看到的这些额外节点,ReadElementContentAsString自动跳转到下一个元素会使事情变得混乱。

这适用于两者 - 在这里,您在获取元素内容之前检查您是否已经在所需的位置,并且只有在您不在的时候才移动。

XmlReader xmlreader = XmlReader.Create(@"..\..\test.xml.txt");

while ((xmlreader.Name == "company") || xmlreader.ReadToFollowing("company"))
{
    Console.WriteLine("Company {0}", xmlreader.ReadElementContentAsString());

    if ((xmlreader.Name == "employees") || xmlreader.ReadToFollowing("employees"))
    {
        Console.WriteLine("Employees{0}", xmlreader.ReadElementContentAsString());
    }
    Console.WriteLine();
}
相关问题