-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathXmlHelper.cs
More file actions
66 lines (58 loc) · 1.75 KB
/
XmlHelper.cs
File metadata and controls
66 lines (58 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Linq;
using System.Text;
using System.Xml;
namespace GemGuide;
public static class XmlHelper
{
public static string FindXPath(this XmlNode node)
{
var builder = new StringBuilder();
while (node != null)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
builder.Insert(0, $"/@{node.Name}");
node = ((XmlAttribute)node).OwnerElement;
break;
case XmlNodeType.Element:
var index = FindElementIndex((XmlElement)node);
builder.Insert(0, $"/{node.Name}[{index}]");
node = node.ParentNode;
break;
case XmlNodeType.Document:
return builder.ToString();
default:
throw new ArgumentException("Only elements and attributes are supported");
}
}
throw new ArgumentException("Node was not in a document");
}
private static int FindElementIndex(XmlElement element)
{
var parentNode = element.ParentNode;
if (parentNode == null)
{
return -1;
}
if (parentNode is XmlDocument)
{
return 1;
}
var parent = (XmlElement)parentNode;
var index = 1;
foreach (var candidate in parent.ChildNodes.OfType<XmlElement>())
{
if (candidate.Name == element.Name)
{
if (candidate == element)
{
return index;
}
index++;
}
}
throw new ArgumentException("Couldn't find element within parent");
}
}