假设我有以下Xml:
<Sections>
<Section>
<Item>
<Field> myfield </Field>
<Field> myfield </Field>
</Item>
<Item>
<Field> myfield </Field>
<Field> myfield </Field>
</Item>
</Section>
<Section>
<Item>
<Field> myfield </Field>
<Field> myfield </Field>
</Item>
</Section>
</Sections>
现在我想要的是遍历部分,并分别处理每个项目,所以我正在考虑做如下事情:
reader.ReadToDescendant("Section")
do
{
Console.WriteLine("Section");
reader.ReadToDescendant("Item");
do
{
var element = (XElement)XNode.ReadFrom(reader);
foreach (XElement el in element.Elements())
{
Console.WriteLine(el.Value);
}
}while(reader.ReadToNextSibling("Item"));
}while (reader.ReadToNextSibling("Section"))
我的问题是。如果我对 Item 节点重复相同的 do-while 循环,阅读器是在找到结束 Section 标记时停止还是在所有 xml 中搜索?我应该使用阅读器吗?在内部循环之前读取子树((?
请注意,我不是在寻找像"使用 XDocument"这样的标准答案。我知道 dom 更容易使用,但它们不适合我的情况
使用
ReadSubtree
创建内部读取器以使用当前节点。否则,读者将不会停止并继续搜索,直到文档结束。
reader.ReadToDescendant("Section");
do
{
Console.WriteLine("Section");
using (var innerReader = reader.ReadSubtree())
{
while (innerReader.ReadToFollowing("Field"))
{
Console.WriteLine("field");
}
}
} while (reader.ReadToNextSibling("Section"));