gpt4 book ai didi

java - 如何使用java从xml(DOM)的多级标签中读取特定元素

转载 作者:行者123 更新时间:2023-12-01 15:08:29 25 4
gpt4 key购买 nike

我想使用java从xml(DOM)读取多级标签,示例xml是:

<root>     <subclass>         <subclass>             <subclass>                 <name>test1</name>                 <address>address1</address>              </subclass>               <name>test2</name>               <address>address2</address>         </subclass>         <name>test3</name>         <address>address3</address>     </subclass> </root> 
How to read <name> test2</name> and <address> address2</address> from the above xml?

I have given a sample code .. but i need to find the values dynamically. when i am iterating bu using subclass tag, it's giving all the data. just i want to know how to get the specific data like <name>test2</name> and <address>address2</address> .

Below is my java code which is reading the above xml:

NodeList fList = firstWordElement
.getElementsByTagName("root");
for (int i = 0; i < fList.getLength(); i++) {
Node firstFLNode = fList.item(i);
if (firstFLNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstWdElement = (Element) firstFLNode;
NodeList firstWdList = firstWdElement.getElementsByTagName("innerclass");

for (int j = 0; j < firstWdList.getLength(); j++) {

Element firstWd1Element = (Element) firstWdList.item(j);

if (firstWd1Element.getNodeType() == Node.ELEMENT_NODE) {
String InnerName = ParseUtil.getTagValue("name", firstWd1Element);
String InnerFormat = ParseUtil.getTagValue("format", firstWd1Element);
String InnerDescription = ParseUtil.getTagValue("description", firstWd1Element);

NodeList innerClassList = firstWd1Element.getElementsByTagName("subclass");

for (int k = 0; k < innerClassList.getLength(); k++) {

Element subClassElement = (Element) innerClassList
.item(k);
if (subClassElement.getNodeType() == Node.ELEMENT_NODE) {
String InnerSubName = ParseUtil.getTagValue("name", subClassElement);
System.out.println("Innername==="+ InnerSubName);
String InnerSubFormat = ParseUtil.getTagValue("format", subClassElement);
System.out.println("Innerformat==="+ InnerSubFormat);
String InnerSubDescription = ParseUtil.getTagValue("description", subClassElement);
System.out.println("Innerdescription==="+ InnerSubDescription);

}
}

}



}
}
}

最佳答案

关于java - 如何使用java从xml(DOM)的多级标签中读取特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12641246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com