我正在用java编写一个简单的XML解析器,
请解释我如何从属性文件中读取 XML 标记名称?示例:如果有类似的 XML 文件
<parent>
<child>1</child>
<child2>2</child2>
</parent>
我想从配置文件中读取标签名称。这是我目前正在处理的代码,我正在使用 test.xml 文件从中读取数据。
public class xml2
{
public void xmlR(File f)
{
try
{
FileInputStream IF=new FileInputStream(f);
DataInputStream data=new DataInputStream(IF);
BufferedReader buf=new BufferedReader(new InputStreamReader(data));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(f);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("test");
File file=new File("xml.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
writer.write("ID : " + getTag("id", eElement));
writer.newLine();
writer.write("Name : " + getTag("Name", eElement));
writer.newLine();
writer.write("AGE: " + getTag("age", eElement));
writer.newLine();
writer.flush();
writer.write("-----------------------");writer.newLine();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static String getTag(String sTag, Element eElement)
{
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
public static void main(String args[])
{
xml2 x=new xml2();
x.xmlR(new File("test.xml"));
}
}