首页 > 解决方案 > XMLReader 读取到下一个未知类型的兄弟

问题描述

我了解我们如何使用如下代码示例。

public class Sample
{
    public static void Main()
    {
        using (XmlReader reader = XmlReader.Create("books.xml"))
        {
            reader.ReadToFollowing("book");
            do
            {
                Console.WriteLine("Name ", reader.GetAttribute("Name"));
            } while (reader.ReadToNextSibling("book"));
        }
    }
}

这将读取“书”类型的每个兄弟姐妹。所以在像下面这样的xml结构中它会很好用..

<Section>
       <book Name="Titan Quest 1"/>
       <book Name="Titan Quest 2"/>
       <book Name="Adventure Willy"/>
       <book Name="Mr. G and the Sandman"/>
       <book Name="Terry and Me"/>
</Section>

但是可以说你的兄弟姐妹并不总是类型 book.. 在部分内部,我们可以有 book、cd、dvd 或 vhs,因此 xml 可能看起来像这样

<Section>
       <cd Name="Titan Quest 1"/>
       <book Name="Titan Quest 2"/>
       <vhs Name="Adventure Willy"/>
       <cd Name="Mr. G and the Sandman"/>
       <dvd Name="Terry and Me"/>
</Section>

我想写一个方法,不管它是什么兄弟类型,它都会给我 Name 属性。使用上面的代码我只会得到 [Titan Quest 2]。这可以做到吗?谢谢!

标签: c#xmlreader

解决方案


将此代码与XDocument一起使用将从属性中获取所有值:

 var document = XDocument.Load("test.xml");

 var bookValues = document.XPathSelectElement("Section")
       .Descendants()
       .Select(x => x.Attribute("Name").Value);

或者使用 XmlReader 获取所有属性值:

List<String> values = new List<string>();
using (var xmlreader = XmlReader.Create("test.xml"))
{
    xmlreader.ReadToDescendant("Section");
    while (xmlreader.Read())
    {
        if (xmlreader.IsStartElement())
        {
            values.Add(xmlreader.GetAttribute("Name"));
        }
    }
}

推荐阅读