Hi, I use following example XML file and want to extract child nodes by given 'paths'.
<?xml version="1.0" encoding="UTF-8"?>
<Element>
<Title ElementID="SL17681">title</Title>
<Element>
<Title ElementID="SL17682">title 2</Title>
<Para id="target022">
Der
<Comment id="SL17882">
<User> Test1 </User>
</Comment>
Anwender
<Comment id="SL17868">
<User> Test2 </User>
</Comment>
muss
<Comment id="WRONG023">
<User> Test3 </User>
</Comment>
sehr
<Comment id="SL17889">
<User> Test4 </User>
</Comment>
viel
<Comment id="SL17872">
<User> Test5 </User>
</Comment>
Geduld
<Comment id="SL17883">
<User> Test6 </User>
</Comment>
aufbringen
<Comment id="SL17916">
<User> Test7 </User>
</Comment>
und
<Comment id="SL17890">
<User> Test8 </User>
</Comment>
sofort
<Comment id="SL17898">
<User> Test9 </User>
</Comment>
damit
<Comment id="SL17880">
<User> Test10 </User>
</Comment>
aufhören
<Comment id="SL17899">
<User> Test11 </User>
</Comment>
zu
<Comment id="SL17885">
<User> Test12 </User>
</Comment>
meckern
<Comment id="SL17878">
<User> Test13 </User>
</Comment>
!
</Para>
<Para id="target023">
und jetzt will ich es wissen!
</Para>
</Element>
</Element>
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import junit.framework.TestCase;
public class XPathTest extends TestCase
{
public void testXPath() throws Exception
{
File xmlContent = new File("PublicContent.xml");// my file see above
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
dbf.setExpandEntityReferences(true);
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc;
InputStream is = new FileInputStream(xmlContent);
doc = db.parse(is);
is.close();
String[] xpaths = new String[] {"//*/*[2]/*[2]", "//*/*[2]/*[3]", "//*/*[2]/*[2]", "//*/*[2]/*[3]"};
for (String sElementPath : xpaths)
{
Element element = (Element) XPathAPI.selectSingleNode(doc.getDocumentElement(), sElementPath);
System.out.println("Path: " + sElementPath + "\tElement Name: " + element.getNodeName() + "\tHit: " + element.getAttribute("id"));
}
}
}
The result shows the following:
Path: //*/*[2]/*[2] Element Name: Para Hit: target022
Path: //*/*[2]/*[3] Element Name: Comment Hit: WRONG023
Path: //*/*[2]/*[2] Element Name: Para Hit: target022
Path: //*/*[2]/*[3] Element Name: Comment Hit: WRONG023
but I expected (or want to get) the following:
Path: //*/*[2]/*[2] Element Name: Para Hit: target022
Path: //*/*[2]/*[3] Element Name: Para Hit: target023
Path: //*/*[2]/*[2] Element Name: Para Hit: target022
Path: //*/*[2]/*[3] Element Name: Para Hit: target023
My question is, does the method selectSingleNode works correct, and how can I get the requestes result from the given paths??
THX!!