[英]Get the name of all attributes in a XML-File
嘿,我有一个XML文件,我想导航到一个给定的节点,并获取该节点的所有属性的名称。
例如:(XML文件)
<RootName>
<SubNode>
<Attribute1>Value 1</Attribute1>
<Attribute2>Value 2</Attribute2>
</SubNode>
</RootName>
到目前为止,这是我的代码:(Java代码)
File file = new File("data.xml");
try
{
/* Parse File */
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
/* Find Starting Tag */
NodeList nodes = doc.getElementsByTagName(StartTag);
for (int i = 0; i < nodes.getLength(); i++)
{
Element element = (Element) nodes.item(i);
System.out.println(element);
}
现在我知道您可以找到一个给定名称的特定属性
String name = element.getAttribute("Attribute1");
但是我想动态地找到所有这些名称。
提前致谢
斯科特
您正在寻找的是元素。 这是有关如何在XML中获取元素的示例:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class DOMElements{
static public void main(String[] arg){
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter XML File name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if(file.exists()){
// Create a factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
// Get a list of all elements in the document
NodeList list = doc.getElementsByTagName("*");
System.out.println("XML Elements: ");
for (int i=0; i<list.getLength(); i++) {
// Get element
Element element = (Element)list.item(i);
System.out.println(element.getNodeName());
}
}
else{
System.out.print("File not found!");
}
}
catch (Exception e) {
System.exit(1);
}
}
}
另请参阅您的问题下方的我的评论,该问题涉及如何正确设计XML,何时使用元素以及何时使用属性。
element.getAttributes();
为您提供org.w3c.dom.NamedNodeMap
。 您可以使用item(int index)
方法遍历此过程,以获取org.w3c.dom.Attr
节点,并从getName()
方法getName()
这些节点的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.