[英]Define how far element is from the root of XML
考慮一個 XML:
<items>
<item id="0001" type="donut">
<name>Cake</name>
<ppu>0.55</ppu>
<batters>
<batter id="1001">Regular</batter>
<batter id="1002">Chocolate</batter>
<batter id="1003">Blueberry</batter>
</batters>
<topping id="5001">None</topping>
<topping id="5002">Glazed</topping>
<topping id="5005">Sugar</topping>
<topping id="5006">Sprinkles</topping>
<topping id="5003">Chocolate</topping>
<topping id="5004">Maple</topping>
</item>
</items>
items 是根,所以距離 == 0
item 直接在根目錄下,因此距離為 1
名稱在 2 級以下,因此距離為 2
如何為 C# 中的 XElement 動態定義這樣的距離?
您應該能夠使用 Parent 屬性,計算步驟直到您到達根:
public int GetElmtDepth(XDocument doc, XElement elmt)
{
var (depth, target) = (0, elmt);
while (target != doc.Root)
(depth, target) = (depth + 1, target.Parent);
return depth;
}
您可以簡化MSDN中的System.Xml.XmlTextReader.Depth
示例以顯示節點元素及其各自的深度:
// XML file to be parsed.
string xmlFilePath = @"C:\test.xml";
// Create the reader.
using XmlTextReader reader = new XmlTextReader(xmlFilePath);
// Parse the XML and display each node.
while (reader.Read())
{
// If node type is an element
// Display element name and depth
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine($"Element = {reader.Name}, Depth = {reader.Depth}");
}
}
Output:
Element = items, Depth = 0
Element = item, Depth = 1
Element = name, Depth = 2
Element = ppu, Depth = 2
Element = batters, Depth = 2
Element = batter, Depth = 3
Element = batter, Depth = 3
Element = batter, Depth = 3
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
未來的讀者可能希望看到計算元素深度的純 XPath 解決方案:
//*[@id="1001"]
。//*[@id="1001"]/ancestor::*
count(//*[@id="1001"]/ancestor::*)
。 正如預期的那樣,這將為給定的 XML 返回3
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.