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.
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/