1

Possible Duplicate:
How to access a xml node with attributes and namespace using selectsinglenode()

I have an XML:

<Root xmlns:XXXlocal="XXXX" schemaVersion="2.7" variant="multiterm">
  <Customers>
    <Customer type="Covered">
      <DataItem name="OpCity" value="" />
      <DataItem name="OpAddress1" value="" />
      <DataItem name="OpAddress2" value="" />
      <DataItem name="OpState" value="MI" />
    <Customer>
  </Customers>
</Root>

I need to get the value "MI" from the above XML. Please note that the XML has many different "Customer Types."

How would I go about doing this? I'm having difficulty writing the xPath query to get it.

Community
  • 1
  • 1
JJ.
  • 9,580
  • 37
  • 116
  • 189

2 Answers2

2

In C#, you can use LINQ/XDocument, and XPathSelectElement() to query with xpath:

var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("l", "XXXX");
var val = document.XPathSelectElement("/l:Root/l:Customers/l:Customer[@type='Covered']/l:DataItem[@name='OpState']/@value", namespaceManager).Value;
wst
  • 11,681
  • 1
  • 24
  • 39
  • XPathException was unhandled. Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function. – JJ. Jan 29 '13 at 01:23
  • Pass the `namespaceManager` to `XPathSelectElement()` as the second parameter. See the updated example. – wst Jan 29 '13 at 15:42
1

Assuming the namespace XXXX is defined as the prefix x, this should work...

/x:Root/x:Customers/x:Customer[@type='Covered']/x:DataItem[@name='OpState']/@value
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95