I read an XML file to an XMLDocument and iterate through its nodes. How do I
get the XPath position (index) of a certain element? For example If I on the
second "b" node I want to get "2":
<a>
<b/>
<c/>
<b/> <--- This one
</a>
Is it possible?
Guy wrote:
As long as there are no namespaces involved the following example shows
you how to count the siblings with the same name that precede the
current node:
string xmlSource = @"<a>
<b/>
<c/>
<b/>
</a>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlSource);
XmlNodeList elements = xmlDocument.GetElementsByTagName("*");
foreach (XmlNode node in elements) {
Console.WriteLine("NodeName: {0}, position: {1}.", node.LocalName,
node.SelectNodes("./preceding-sibling::" +
node.LocalName).Count + 1);
}
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
It seems that this is what I need, but unfortunately I do have namespaces ...
Can you instruct me how to do it?
Many thanks in advance!
Guy wrote:
> It seems that this is what I need, but unfortunately I do have namespaces ...
> Can you instruct me how to do it?
With the following changes the results should be correct to find the
position in terms of elements with the same local name and the same
namespace URI:
string xmlSource = @"<a xmlns=""http://example.com/ns1"">
<b/>
<b xmlns="""" />
<pf2:b xmlns:pf2=""http://examle.com/ns2"" />
<c/>
<pf2:b xmlns:pf2=""http://examle.com/ns2"" />
<b/>
<b/>
<pf3:c xmlns:pf3=""http://example.com/ns1"" />
</a>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlSource);
XmlNodeList elements = xmlDocument.GetElementsByTagName("*");
foreach (XmlNode node in elements) {
const string prefix = "pf";
string xPathExpression;
XmlNamespaceManager xmlNamespaceManager = new
XmlNamespaceManager(xmlDocument.NameTable);
if (node.NamespaceURI != null) {
xmlNamespaceManager.AddNamespace(prefix, node.NamespaceURI);
xPathExpression = "./preceding-sibling::" + prefix + ":" +
node.LocalName;
}
else {
xPathExpression = "./preceding-sibling::" + node.LocalName;
}
Console.WriteLine("{{{0}}}{1}, position: {2}.",
node.NamespaceURI, node.LocalName,
node.SelectNodes(xPathExpression, xmlNamespaceManager).Count + 1
);
Console.WriteLine();
}
Result here is
{http://example.com/ns1}a, position: 1.
{http://example.com/ns1}b, position: 1.
{}b, position: 1.
{http://examle.com/ns2}b, position: 1.
{http://example.com/ns1}c, position: 1.
{http://examle.com/ns2}b, position: 2.
{http://example.com/ns1}b, position: 2.
{http://example.com/ns1}b, position: 3.
{http://example.com/ns1}c, position: 2.
Give some feedback in the group whether that is what you want and it
works for you as intended.