親ノードの下に 2 つのノードが存在する場合、ノードの値を取得するにはどうすればよいですか。例: 次の Xml があります。
<?xml version="1.0" encoding="UTF-8"?>
<Services xmlns="http://sample.schema.com/abc">
<service>
<name>Sample</name>
<uri>/v9.0/sample.123.com
</uri>
</service>
<service>
<name>Sample 2</name>
</service>
<service>
<name>Sample 3</name>
<uri>/v9.0/sample3.123.com
</uri>
</service>
<service>
<name>Sample 4</name>
<uri>/v9.0/sample4.123.com
</uri>
</service>
<service>
<name>Sample 5</name>
<uri>/v9.0/sample5.123.com
</uri>
</service>
<service>
<name>Sample 6</name>
</service>
<service>
<name>Sample 7</name>
<uri>/v9.0/sample7.123.com
</uri>
</service>
<service>
<name>Sample 8</name>
</service>
</Services>
私のコード:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class SimpleXpath {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(false); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("testService1.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//Services/service[(name) and (uri)/text()]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
String value=nodes.item(i).getNodeValue();
System.out.println(" output : "+i+" "+value);
}
}
}
name と uri が service ノードの下にある場合、上記の xml から name と url の値を読み取りたい。一部のサービス ノードには名前のみが含まれていることがわかります。そっちは避けたい。私の xpath 式は出力として null 値を与えます。
サービスに両方が含まれている場合、名前と uri の「テキスト」を取得するにはどうすればよいですか?
xpath を使用して、名前を最初に、uri を 2 番目として出力を取得できますか (両方がサービスの下にある場合)。
どうもありがとう。
ジョン