编辑:更新了 XML 文件
要求:
需要从所有标签中读取属性名称值。
示例 XML 文件:
<ObjectConfig>
<ObjectAttribute name="A">
<ListenerRule>
<Reference name="B">
<ListenerRule>
<AttributeSource name="C">
<ApplicationRef>
<Reference name="D">
</ApplicationRef>
<RuleRef>
<Reference name="E">
</RuleRef>
</AttributeSource>
<AttributeTargets >
<AttributeTarget name="F">
<ApplicationRef>
<Reference name="G">
<ApplicationRef>
</AttributeTargets>
</ObjectAttribute>
<ObjectAttribute name="H">
<ListenerRule>
<Reference name="I">
<ListenerRule>
<AttributeSource name="J">
<ApplicationRef>
<Reference name="K">
</ApplicationRef>
<RuleRef>
<Reference name="L">
</RuleRef>
</AttributeSource>
<AttributeTargets >
<AttributeTarget name="M">
<ApplicationRef>
<Reference name="N">
<ApplicationRef>
</AttributeTargets>
</ObjectAttribute>
</ObjectConfig>
检查下面的代码及其描述
这是我的java代码。我能够获取 ObjectAttribute 标记的名称属性。希望获取 ObjectConfig 中所有其他标签的名称属性。
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class XmlTest {
public static void main(String[] args) {
try {
File inputFile = new File("xmlPrueba.xml");
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"+doc.getDocumentElement().getNodeName());
NodeList ObjectAttributeList = doc.getElementsByTagName("ObjectAttribute");
for (int temp = 0; temp < ObjectAttributeList.getLength(); temp++) {
Node ObjectAttributeNode = ObjectAttributeList.item(temp);
if (ObjectAttributeNode.getNodeType() == Node.ELEMENT_NODE) {
Element ObjectAttributeElement = (Element) ObjectAttributeNode;
System.out.println("Object Attribute Name : "
+ ObjectAttributeElement.getAttribute("name"));
NodeList ListenerRuleList = ObjectAttributeNode.getChildNodes();
for (int i = 0; i < ListenerRuleList.getLength(); i++) {
Node ListenerRuleNode = ListenerRuleList.item(i);
if (ListenerRuleNode.getNodeType() == Node.ELEMENT_NODE) {
NodeList ListenerReferenceRuleList = ListenerRuleNode.getChildNodes();
for(int j=0; j<ListenerReferenceRuleList.getLength(); j++){
Node ListenerReferenceRuleNode = ListenerReferenceRuleList.item(j);
if(ListenerReferenceRuleNode.getNodeType() == Node.ELEMENT_NODE){
Element ListenerReferenceRuleElement = (Element) ListenerReferenceRuleNode;
System.out.println("Listener Attribute Name : "
+ ListenerReferenceRuleElement.getAttribute("name"));
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} }