xeoshow
xeoshow

Reputation: 37

How to define xpath for below xml data?

I have a xml data as below:

<list>
    <com.domain.Products>
        <cla__id>
          <cname>class1</cname>
          <id>1</id>
        </cla__id>
        <name>pname1</name>
        <id>1</id>
    </com.domain.Products>

    <com.domain.Products>
        <cla__id reference="../../com.domain.Products/cla__id"/>
        <name>pname2</name>
        <id>2</id>
    </com.domain.Products>
</list>

I want to use the xpath to get the value for cname node (the value is 'class1'), while for the second com.domain.Products node, it just has a reference to the cla__id node, which is exactly the same as the one of first com.domain.Products node...

So, the cname for the second com.domain.Products node is actually the same as first com.domain.Products node, both are 'class1', but if I use cla__id/cname xpath to get the value, I can only get it correctly for the first com.domain.Products node, second com.domain.Products node will only have a blank value, which is wrong.

How to achieve the correct result? Thanks a lot.

attach: My current smartgwt java code doing it this way:

......
private ProductsDS(String id) {
String recordName = "com.domain.Products";
setID(id);
setDataFormat(DSDataFormat.XML);
setRecordXPath("//" + recordName);

DataSourceField pkField = new DataSourceField("id", FieldType.INTEGER, "id");
pkField.setHidden(true);
pkField.setPrimaryKey(true);
DataSourceField claIdField = new DataSourceField("cla__id/cname", FieldType.TEXT, "classtype");
claIdField.setValueXPath("cla__id/cname");
......

ps: just re-edit twice to make the post better..

Upvotes: 1

Views: 532

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243449

It is not possible in XPath 1.0 and XPath 2.0 to perform dynamic (not contained in the XPath expression, but generated) XPath expressions.

Therefore, it is not possible to dynamically evaluate a reference to an element, embedded in another XML element, where the reference is an XPath expression.

Proposed solution: Provide a new way to uniquely identify an element (such as giving it a unique id attribute) and use the value of this attribute as the reference to the element:

<list>
    <com.domain.Products>
        <cla__id>
            <cname>class1</cname>
            <id>1</id>
        </cla__id>
        <name>pname1</name>
        <id>1</id>
    </com.domain.Products>
    <com.domain.Products>
        <cla__id reference="1"/>
        <name>pname2</name>
        <id>2</id>
    </com.domain.Products>
</list>

Then, the cname value for the com.domain.Products element having id of 2 is:

/*/*
  [id
  = 
   /*/*[id=2]/cla__id/@reference]
                           /cla__id/cname/text()

Upvotes: 1

Related Questions