XML question

Status
Not open for further replies.

phoenix108

Wise, Aged Ars Veteran
106
Let's say I've created this XML document. How can I search for a node (call it node A) whose id attribute is a certain value, and then find the parentnode of node A?

Code:
 <structure>
  <main name="Personal" id="/personal/">
    <file name="About Me" id="/about.aspx" />
    <file name="Contact Me" id="/contact.aspx" />
    <folder name="Resume" id="/resume/" />
    <folder name="Research" id="/research/ ">
      <folder name="svm" id="/research/svms/" />
    </folder>
  </main>
  <main name="Business" id="/business/" />
  <main name="Network" id="network/"  />
</structure>
 

fualix927

Seniorius Lurkius
7
With this code:
Code:
 <structure>
  <main name="Personal" id="/personal/">
    <file name="About Me" id="/about.aspx" />
    <file name="Contact Me" id="/contact.aspx" />
    <folder name="Resume" id="/resume/" />
    <folder name="Research" id="/research/ ">
      <folder name="svm" id="/research/svms/" />
    </folder>
  </main>
  <main name="Business" id="/business/" />
  <main name="Network" id="network/"  />
</structure>

First Identify the node via xpath, then use the parent node property:
Code:
dim the_node as XMLNode
dim parent_node as XMLNode
dim xpath_query as string = "//*[@id='research/svms/']" 

'First check if the xpath points to a node
if some_xml_doc.selectNodes(xpath_query).Count > 0 then

  'Get the node
  the_node = some_xml_doc.SelectSingleNode()

  'Get the parent (you may wanna throw this in a try/catch
  'Just in case it doesn't have a parent, or atleast make
  'sure the "the_node" is not the DocumentElement.
  parent_node = the_node.ParentNode

end if
 

TheJet

Ars Praefectus
4,598
Subscriptor++
The XPath query you want should be:

//*[@id = '<what to compare against>']/ancestor::*[position() = 1]

Which says:

give me all immediate ancestor nodes (i.e. parents) of all nodes in the tree whose id attribute equals '<what to compare against>'.

You can use this XPath with the selectNodes() [which will return you all nodes in the tree which match the query], or with selectSingleNode() [which will return just the first (in document order) node in the tree which matches the query].

TheJet

P.S. It's early, so the above statement may not work "out of box"

EDIT: See I told you, I missed a ']' :)
 

phoenix108

Wise, Aged Ars Veteran
106
When I enter in that, I get this error:

Expected token 'eof' found ':'. //*[@id = '<query>']/ancestor-->:<--:*[position() = 1]

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: Expected token 'eof' found ':'. //*[@id = '<query>']/ancestor-->:<--:*[position() = 1]
 
Status
Not open for further replies.