code_junkie

Best way test for XPath existence in an XML file?

Nov 11th, 2011
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. <foo>
  2. <bar baz="This is the value of the attribute named baz">
  3. </foo>
  4.  
  5. XPathDocument document = new XPathDocument(filename);
  6. XPathNavigator navigator = document.CreateNavigator();
  7. XPathNavigator node = navigator.SelectSingleNode("//foo/bar");
  8. if(node.HasAttributes)
  9. {
  10. Console.WriteLine(node.GetAttribute("baz", string.Empty));
  11. }
  12.  
  13. XDocument doc = XDocument.Load("foo.xml");
  14.  
  15. var att = from a in doc.Descendants("bar")
  16. select a.Attribute("baz")
  17.  
  18. foreach (var item in att) {
  19. if (item != null) { ... }
  20. }
  21.  
  22. var node = XDocument.Load(filename)
  23. .Descendants("bar")
  24. .SingleOrDefault(e=>e.Attribute("baz") != null);
  25.  
  26. if (node != null) Console.WriteLine(node.Attribute("baz").Value);
  27.  
  28. var baz = navigator.SelectSingleNode("//foo/bar/@baz");
  29. if (baz != null) Console.WriteLine(baz);
  30.  
  31. var doc = XDocument.Load(fileName);
  32.  
  33. var results = from r in doc.XPathSelectElements("/foo/bar[count(@baz) > 0]")
  34. select r.Attribute("baz");
  35.  
  36. foreach (String s in results)
  37. Console.WriteLine(s);
Add Comment
Please, Sign In to add comment