C# SelectSingleNode with NameSpace issues
I am using C# (.NET 2.0) -- actually trying to have it working on Mac OS X using MONO (I don't think MONO is the issue)
Given the following XML fragment which has been retrieved as a XmlNode from a bigger XmlDocument:
<subc开发者_开发问答ategoryCode xmlns="uuid:7E1158D2-DA42-4048-8513-66B4D48FA992">N100</subcategoryCode>
<subcategoryName xmlns="uuid:7E1158D2-DA42-4048-8513-66B4D48FA992">DJ Headphones</subcategoryName>
<products xlink:href="tcm:5-33975" xlink:title="TESTONE Composition" xlink:type="simple" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="uuid:7E1158D2-DA42-4048-8513-66B4D48FA992" />
<products xlink:href="tcm:5-54295" xlink:title="HPX2000 Composition" xlink:type="simple" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="uuid:7E1158D2-DA42-4048-8513-66B4D48FA992" />
<products xlink:href="tcm:5-54296" xlink:title="HPX4000 Composition" xlink:type="simple" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="uuid:7E1158D2-DA42-4048-8513-66B4D48FA992" />
I am trying to retrieve subcategoryName using SelectSingleNode but I simply cannot. This is my code:
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace(String.Empty, "uuid:7E1158D2-DA42-4048-8513-66B4D48FA992");
XmlNodeList subcatList = doc.GetElementsByTagName("subcategories");
foreach (XmlNode subcat in subcatList) {
html += "<div id=\"";
html += subcat.SelectSingleNode("subcategoryName", nsm).InnerText; // <-- HERE IS MY PROBLEM!!!
html += "\" class=\"product_thumbs_holder\" style=\"display: block; \">";
html += "</div>";
html += "<div style=\"clear:both\"></div>";
}
I believe the issue is probably related to the way I am handling the Namespace but I have been stuck on this for hours. I have tried a bunch of similar AddNamespace declarations with no luck.
Anyone out there would be kind enough to provide any pointers to where the issue is?
XPath doesn't work with default namespaces. You must create a prefix for the namespace. This code should work:
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace("x", "uuid:7E1158D2-DA42-4048-8513-66B4D48FA992");
XmlNodeList subcatList = doc.GetElementsByTagName("subcategories");
foreach (XmlNode subcat in subcatList) {
html += "<div id=\"";
html += subcat.SelectSingleNode("x:subcategoryName", nsm).InnerText; // <-- HERE IS MY PROBLEM!!!
html += "\" class=\"product_thumbs_holder\" style=\"display: block; \">";
html += "</div>";
html += "<div style=\"clear:both\"></div>";
}
Note: you don't need to add the prefix in de xml document. The prefixes in the xml document and the prefixes in the code don't have to match, as long as the associated namespaces match.
Try getting the subcategoryName
directly:
XmlNodeList subcatList = xmldoc.GetElementsByTagName( "subcategoryName" );
foreach( XmlNode subcat in subcatList )
{
Console.WriteLine( subcat.InnerText );
}
This will get all of the subcategoryName
elements in the xml file.
精彩评论