all groups > dotnet xml > april 2005 >
You're in the

dotnet xml

group:

XPath syntax to check an attribute of all child nodes?



XPath syntax to check an attribute of all child nodes? Bob
4/29/2005 3:35:57 PM
dotnet xml: I have sitemap like XML, of which every element has an attribute "url", e.g.

<record menu_id="240" name="Countries and States" url="Countries.aspx">
<record2 page_id="54" url="CountriesEdit.aspx" />
<record3 page_id="27" url="Regions.aspx">
<record4 page_id="55" url="RegionsEdit.aspx" />
</record3>
</record>

I need to compare whether a string value contains the url or not. If so,
get the node. Here's my code:

XmlNode n = xml.SelectSingleNode("//*[contains('" + myString + "', @url)]");

This doesn't work. I know it works against the "record" node if the XPath
is //record[......]. How can I make it to search every element node
regardless of the name?

Thanks a lot
Bob

Re: XPath syntax to check an attribute of all child nodes? Martin Honnen
4/30/2005 12:00:00 AM


[quoted text, click to view]

The code and the XPath expression look fine to me, here is a complete
console example

public static void Main (string[] args) {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"test2005043001.xml");
XmlNode node = xmlDocument.SelectSingleNode("//*[contains('" +
args[0] + "', @url)]");
if (node != null) {
Console.WriteLine("Found node {0} with type {1}.", node,
node.NodeType);
}
else {
Console.WriteLine("No matching node found.");
}
}

if you pass on the argument Regions.aspx on the command line for
instance then the matching element node is found.

--

Martin Honnen --- MVP XML
Re: XPath syntax to check an attribute of all child nodes? Bob
5/2/2005 3:47:34 PM
HI Martin:

I ran your code against the sample XML I gave and it works. However, my
real XML has many "record" elements, and it somehow just returns the entire
XML tree. The url is unique across all elements but it somhow just doesn't
return the single element.

Is there a way to look for the element name "record*" since the element
names are "record", "record1", "record2" etc.?

Thanks again
Bob


[quoted text, click to view]

AddThis Social Bookmark Button