user2378036
user2378036

Reputation: 5

Xmlnode how to see if the node exist or not

I need some help to check if a node exist.

I can select the node like this

node["sa:name1"]["sa:name2"]["sa:name3"]

And this works fine but if the node doesn't exsist I get an error I have tried this

if(node.SelectSingleNode("/sa:name1/sa:name2/sa:name3") != null)

but this dident help this just makes a new error

An exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll but was not handled in user code

Additional information: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

Upvotes: 0

Views: 1144

Answers (3)

Martin Honnen
Martin Honnen

Reputation: 167726

Use http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.addnamespace.aspx

XmlNamespaceManager nsMgr = new XmlNamespaceManager(node.OwnerDocument.NameTable);

nsMgr.AddNamespace("sa", "http://example.com/");

XmlNode selected = node.SelectSingleNode("/sa:name1/sa:name2/sa:name3", nsMgr);
if (selected != null)
{
  ...
}

Instead of http://example.com/ you need of course to use the URI of the nodes in the input document, I think the namespace URI is http://rep.oio.dk/uvm.dk/studieadm/common/xml/schemas/2006/02/20/.

Upvotes: 1

DGibbs
DGibbs

Reputation: 14618

You need to add a namespace manager for the document before your call to SelectSingleNode:

XmlNamespaceManager xmlnsMan = new XmlNamespaceManager(xml.NameTable);
xmlnsMan.AddNamespace("sa", "[namespace]);

Upvotes: 0

Oscar
Oscar

Reputation: 13990

The error is clear: You need to add a namespace manager to your code for your xpath query to work. Use the overloaded version of SelectSingleNode() which accepts an instance of XmlNamespaceManager as argument.

  XmlDocument doc = new XmlDocument();
  doc.Load("booksort.xml");

  //Create an XmlNamespaceManager for resolving namespaces.
  XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
  nsmgr.AddNamespace("bk", "urn:samples");

  //Select the book node with the matching attribute value.
  XmlNode book;
  XmlElement root = doc.DocumentElement;
  book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr);

  Console.WriteLine(book.OuterXml);

http://msdn.microsoft.com/en-us/library/h0hw012b(v=vs.110).aspx

Upvotes: 0

Related Questions