xml文字列のすべてのノード名、ノード値、および属性を読み取るxpath式を作成する際に助けが必要です。私はこれを作った:Java、XPathすべてのノード名、ノード値、および属性を読み取る式
private List<String> listOne = new ArrayList<String>();
private List<String> listTwo = new ArrayList<String>();
public void read(String xml) {
try {
// Turn String into a Document
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
// Setup XPath to retrieve all tags and values
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET);
// Iterate through nodes
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
listOne.add(node.getNodeName());
listTwo.add(node.getNodeValue());
// Another list to hold attributes
}
} catch(Exception e) {
LogHandle.info(e.getMessage());
}
}
私は式//text()[normalize-space()='']
をオンラインで見つけました。ただし、動作しません。ノード名をlistOne
から取得しようとすると、ちょうど#text
になります。私は//
を試しましたが、それはどちらもうまくいきません。私が持っていた場合は、このXML:
<Data xmlns="Somenamespace.nsc">
<Test>blah</Test>
<Foo>bar</Foo>
<Date id="2">12242016</Date>
<Phone>
<Home>5555555555</Home>
<Mobile>5555556789</Mobile>
</Phone>
</Data>
listOne[0]
がData
を保持する必要がありますlistOne[1]
がTest
を保持する必要がありますlistTwo[1]
はblah
などを保持する必要があり、...すべての属性は、別の並列リストに保存されます。
xPath
はどのような式を評価する必要がありますか?
注:XML文字列には異なるタグを使用できるため、何もハードコードできません。
更新:このループを試しましたが:
NodeList nodeList = (NodeList) xPath.evaluate("//*", document, XPathConstants.NODESET);
// Iterate through nodes
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
listOne.add(i, node.getNodeName());
// If null then must be text node
if(node.getChildNodes() == null)
listTwo.add(i, node.getTextContent());
}
しかし、これが唯一のルート要素Data
を取得し、その後、ちょうど停止します。
です。「text()」は要素の内容を参照しています。 XMLの例では、「blah」、「bar」、および「12242016」はテキストノードです。したがって、 'text()'はおそらくあなたが望むものではありません。 – VGR
ありがとう! 'text()'が要素の内容を与えるなら、 'node()'はノードを与えますか? – syy
私はいくつかの明確化が必要かもしれないと思います。 XMLでは、「ノード」は、テキスト、コメント、処理命令などを含むXML文書内のすべての可能な情報を指し、「要素」は、開始タグと一致する終了タグのいずれかからなる情報を指すか、または単一の自己閉鎖タグ( ' ')。あなたは本当にすべてのノード、あるいはすべての要素とその属性を読みたいのですか? –
VGR