简体   繁体   中英

XML xpath, get the child of root element

Below XML is provided for example.

      <?xml version="1.0" encoding="utf-8"?>
      <store d:mi="22">
           <book price="12.99" d:price="Number" d:mi="4">
                  <title d:constr="String" d:mi="1">Sword of Honour</title>
                  <category d:constr="String" d:mi="2">fiction</category>
                  <author d:constr="String" d:mi="3">Evelyn Waugh</author>
           </book>
           <book price="8.99" d:price="Number" d:mi="9">
               <sublist>
                  <title d:constr="String" d:mi="5">Moby Dick</title>
                  <category d:constr="String" d:mi="6">fiction</category>
                  <author d:constr="String" d:mi="7">Herman Melville</author>
                  <isbn d:constr="String" d:mi="8">0-553-21311-3</isbn>
               </sublist>
           </book>
           <Note price="8.95" d:price="Number" d:mi="13">
                  <title d:constr="String" d:mi="10">50</title>
                  <category d:constr="String" d:mi="11">reference</category>
                  <author d:constr="String" d:mi="12">Nigel Rees</author>
           </Note>
           <Note price="22.99" d:price="Number" d:mi="18">
                  <title d:constr="String" d:mi="14">The Lord of the Rings</title>
                  <category d:constr="String" d:mi="15">fiction</category>
                  <author d:constr="String" d:mi="16">J. R. R. Tolkien</author>
                  <isbn d:constr="String" d:mi="17">0-395-19395-8</isbn>
           </Note>
      </store>

Using the below Xpath I'm able to get the store element.

   String name = "String";
   String xpath = "//title[@d:constr='" + name + "']/parent::store";

But we need to get book(Anything may come which we Don't know) which is the child of store(constant word). Is it possible to do that?

Try to use below expression to match parent of required title ignoring node name:

String name = "String";
String xpath = "//title[@d:constr='" + name + "']/parent::*";

Also note that store is not parent of title , you should use "//title/ancestor::store" instead of "//title/parent::store"

If you simply want to get child of store :

//store/child::*

First child:

//store/child::*[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM