如何获取特定的XML元素参数值?

时间:2022-11-27 17:33:28

i begin parsing xml document and have question: How to get specific XML element parameter value on Java?

我开始解析xml文档并有疑问:如何在Java上获取特定的XML元素参数值?

XML document:

XML文档:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
<keyword name="text123">
    <profile num="1">
        <url>http://www.a.com</url>
        <field-1 param="">text</field-1>
        <filed-2 param="">text</field-2>
    </profile>
    <profile num="2">
        <url>http://www.b.com</url> 
        <field-1 param="">text</field-1>
        <filed-2 param="">text</field-2>
    </profile>
</keyword>
<keyword name="textabc123">
    <profile num="1">
        <url>http://www.1a.com</url>
        <field-1 param="">text</field-1>
        <filed-2 param="">text</field-2>
    </profile>
    <profile num="2">
        <url>http://www.1b.com</url> 
        <field-1 param="">text</field-1>
        <filed-2 param="">text</field-2>
    </profile>
</keyword>
</data>

code i write on Java:

我在Java上写的代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File xml_file=new File("file.xml");
if (xml_file.isFile() && xml_file.canRead()) {
 Document doc = builder.parse(xml_file);
 Element root = doc.getDocumentElement();
 NodeList nodel = root.getChildNodes();
 for (int a = 0; a < nodel.getLength(); a++) {
  String data = /* code i don't know to write*/
  System.out.println(data);
 }
} else {}

i want to out to console element "keyword" parameter "name" value:

我想出去控制台元素“关键字”参数“名称”值:

text123

text123

and

text123abc

text123abc

Please help, Thanks.

请帮忙,谢谢。

4 个解决方案

#1


4  

Node node = nodel.item(a);
if(node instanceof Element) {
  data = ((Element)node).getAttribute("name");
  System.out.println(data);
}

#2


5  

You can use XPath

您可以使用XPath

InputStream is = getClass().getResourceAsStream("somefile.xml");
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = xmlFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.parse(is);
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();

String text123 = (String) xpath.evaluate("/data/keyword[1]/@name", xmlDoc, XPathConstants.STRING);
String textabc123 = (String) xpath.evaluate("/data/keyword[2]/@name", xmlDoc, XPathConstants.STRING);

#3


5  

I'll guide you how to do it using JAXB.

我将指导您如何使用JAXB来完成它。

First of all, your XML is not well formed. You've got filed instead of field on few places.

首先,您的XML格式不正确。在少数几个地方你已经归档而不是现场。

Proper XML:

适当的XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
<keyword name="text123">
    <profile num="1">
        <url>http://www.a.com</url>
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
    <profile num="2">
        <url>http://www.b.com</url> 
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
</keyword>
<keyword name="textabc123">
    <profile num="1">
        <url>http://www.1a.com</url>
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
    <profile num="2">
        <url>http://www.1b.com</url> 
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
</keyword>
</data>

Next, go to this website and download Trang.

接下来,访问该网站并下载Trang。

Assuming your XML file is named sample.xml, run it through Trang using java -jar trang.jar sample.xml sample.xsd to obtain an xsd schema for your xml file.

假设您的XML文件名为sample.xml,请使用java -jar trang.jar sample.xml sample.xsd通过Trang运行它,以获取xml文件的xsd架构。

Now, run xjc sample.xsd (xjc is a tool for generating Java classes for an XML schema, it's bundled with Java 6 SDK).

现在,运行xjc sample.xsd(xjc是一个用于为XML模式生成Java类的工具,它与Java 6 SDK捆绑在一起)。

You'll get a list of Java classes:

您将获得一个Java类列表:

generated\Data.java
generated\Field1.java
generated\Field2.java
generated\Keyword.java
generated\ObjectFactory.java
generated\Profile.java

Put them in your Java project file, and put sample.xml where your program can find it. Now, this is how you get keyword names:

将它们放在Java项目文件中,并将sample.xml放在程序可以找到的位置。现在,这就是获取关键字名称的方式:

JAXBContext context = JAXBContext.newInstance(Data.class);
Data data = (Data)context.createUnmarshaller().unmarshal(new File("sample.xml"));

List<Keyword> keywords = data.getKeyword();

for (Keyword keyword : keywords) {
    System.out.println(keyword.getName());
}

This method might seem a bit messy at start, but if your XML structure doesn't change, I find it nicer to deal with typed Java objects than with DOM itself.

这个方法在开始时可能看起来有些混乱,但是如果你的XML结构没有改变,我发现处理类型化的Java对象比使用DOM本身更好。

#4


0  

The node list contains nodes, which are in fact instances of subinterfaces (Element, Text, etc.).

节点列表包含节点,这些节点实际上是子接口(元素,文本等)的实例。

This code should thus work :

因此,此代码应该起作用:

Node node = nodel.item(a);
if (node instanceof Element) {
    Element e = (Element) node;
    System.out.println(e.getAttribute("name");
}

#1


4  

Node node = nodel.item(a);
if(node instanceof Element) {
  data = ((Element)node).getAttribute("name");
  System.out.println(data);
}

#2


5  

You can use XPath

您可以使用XPath

InputStream is = getClass().getResourceAsStream("somefile.xml");
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = xmlFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.parse(is);
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();

String text123 = (String) xpath.evaluate("/data/keyword[1]/@name", xmlDoc, XPathConstants.STRING);
String textabc123 = (String) xpath.evaluate("/data/keyword[2]/@name", xmlDoc, XPathConstants.STRING);

#3


5  

I'll guide you how to do it using JAXB.

我将指导您如何使用JAXB来完成它。

First of all, your XML is not well formed. You've got filed instead of field on few places.

首先,您的XML格式不正确。在少数几个地方你已经归档而不是现场。

Proper XML:

适当的XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
<keyword name="text123">
    <profile num="1">
        <url>http://www.a.com</url>
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
    <profile num="2">
        <url>http://www.b.com</url> 
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
</keyword>
<keyword name="textabc123">
    <profile num="1">
        <url>http://www.1a.com</url>
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
    <profile num="2">
        <url>http://www.1b.com</url> 
        <field-1 param="">text</field-1>
        <field-2 param="">text</field-2>
    </profile>
</keyword>
</data>

Next, go to this website and download Trang.

接下来,访问该网站并下载Trang。

Assuming your XML file is named sample.xml, run it through Trang using java -jar trang.jar sample.xml sample.xsd to obtain an xsd schema for your xml file.

假设您的XML文件名为sample.xml,请使用java -jar trang.jar sample.xml sample.xsd通过Trang运行它,以获取xml文件的xsd架构。

Now, run xjc sample.xsd (xjc is a tool for generating Java classes for an XML schema, it's bundled with Java 6 SDK).

现在,运行xjc sample.xsd(xjc是一个用于为XML模式生成Java类的工具,它与Java 6 SDK捆绑在一起)。

You'll get a list of Java classes:

您将获得一个Java类列表:

generated\Data.java
generated\Field1.java
generated\Field2.java
generated\Keyword.java
generated\ObjectFactory.java
generated\Profile.java

Put them in your Java project file, and put sample.xml where your program can find it. Now, this is how you get keyword names:

将它们放在Java项目文件中,并将sample.xml放在程序可以找到的位置。现在,这就是获取关键字名称的方式:

JAXBContext context = JAXBContext.newInstance(Data.class);
Data data = (Data)context.createUnmarshaller().unmarshal(new File("sample.xml"));

List<Keyword> keywords = data.getKeyword();

for (Keyword keyword : keywords) {
    System.out.println(keyword.getName());
}

This method might seem a bit messy at start, but if your XML structure doesn't change, I find it nicer to deal with typed Java objects than with DOM itself.

这个方法在开始时可能看起来有些混乱,但是如果你的XML结构没有改变,我发现处理类型化的Java对象比使用DOM本身更好。

#4


0  

The node list contains nodes, which are in fact instances of subinterfaces (Element, Text, etc.).

节点列表包含节点,这些节点实际上是子接口(元素,文本等)的实例。

This code should thus work :

因此,此代码应该起作用:

Node node = nodel.item(a);
if (node instanceof Element) {
    Element e = (Element) node;
    System.out.println(e.getAttribute("name");
}