c# - 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]。这可以做到吗?谢谢!
解决方案
将此代码与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"));
}
}
}
推荐阅读
- java - 通过 WebView (AndroidStudio) 导航到时,Youtube 在应用程序中启动
- php - Convert html form array to formated json array
- python - 从 cartopy 生成的图像图中获取显示协调
- python-3.x - mode = 'w' 仅适用于 logging.FileHandler 但不适用于 logging.handlers.RotatingFileHandler
- python - Split dictionary into 2 dictionaries by specifying which key-value pair is to be inserted in new dictionary
- javascript - 如何在 JavascriptCore 中运行测试?
- image - unable to load image in react native
- android - 无法将 onClick 分配给 kotlin 中的按钮
- android - 如何从表中获取最后一个rowid
- excel - 后期绑定编译错误:在 Excel VBA 中未定义引用 Outlook 邮件项的用户定义类型