I have written a little C# to parse through a number of elements in an XML document and return only the first of those elements which have a distinct child structure? For example, if I have the following XML doc, then a call to rootElement.DistinctStructures("base")
let's say returns an IEnumerable<XElement>
containing just the base elements with ids 1, 3, and 5.
<root>
<base id="1">
<a>text</a>
</base>
<base id="2">
<a>more text</a>
</base>
<base id="3">
<b>text</b>
</base>
<base id="4">
<a>other text</a>
</base>
<base id="5">
<a>
<c>sub text</c>
</a>
</base>
</root>
The basic code generates a unique key from the element name and text nodes in the structure and compares them to a saved collection of unique elements. My question is whether there is a neater way to do this?
private Dictionary<string, XElement> uniqueElements = new Dictionary<string, XElement>();
public void Go()
{
foreach (var entry in xmlDoc.Elements("e"))
{
string keyString = AsStructureString(entry).ToString();
if (!uniqueElements.Keys.Contains(keyString))
{
uniqueElements.Add(keyString, entry);
}
}
}
public StringBuilder AsStructureString(this XElement input)
{
StringBuilder sb = new StringBuilder(input.Name.LocalName);
var NodesOfNote = input.Nodes().Where(n => n.NodeType == XmlNodeType.Element || n.NodeType == XmlNodeType.Text).ToList();
if (NodesOfNote.Any())
{
sb.Append(">>");
}
foreach (var childNode in NodesOfNote)
{
if (childNode.NodeType == XmlNodeType.Element)
{
sb.Append((childNode as XElement).AsStructureString());
}
if (childNode.NodeType == XmlNodeType.Text)
{
sb.Append("txt");
}
if (!childNode.IsLastIn(NodesOfNote))
{
sb.Append("|");
}
}
return sb;
}
It might be easier than you think. If what determines the structure of a node is its elements and text (regardless of the content), you could do this:
IEnumerable<XElement> DistinctStructures(XContainer root, XName name)
{
return
from d in root.Descendants(name)
group d by GetKey(d) into g
select g.First();
string GetKey(XElement n) =>
String.Join(",",
n.DescendantNodes().Select(d =>
d is XElement e ? $"{e.Name}^{GetDepth(e)}"
: d is XText t ? $"<text>^{GetDepth(t)}"
: default
)
);
int GetDepth(XObject o)
{
var depth = 0;
for (var c = o; c != null; c = c.Parent)
++depth;
return depth;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.