首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得特定的XML元素参数值?

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

Stack Overflow用户
提问于 2011-01-21 12:17:15
回答 3查看 42.6K关注 0票数 4

我开始解析xml文档并提出问题:如何在Java上获得特定的XML元素参数值?

XML文档:

代码语言:javascript
复制
<?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>

我在Java上编写的代码:

代码语言:javascript
复制
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 {}

我想输出到控制台元素“关键字”参数"name“值:

text123

text123abc

帮帮忙,谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-01-21 12:23:39

代码语言:javascript
复制
Node node = nodel.item(a);
if(node instanceof Element) {
  data = ((Element)node).getAttribute("name");
  System.out.println(data);
}
票数 4
EN

Stack Overflow用户

发布于 2011-01-21 12:30:55

您可以使用XPath

代码语言:javascript
复制
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);
票数 5
EN

Stack Overflow用户

发布于 2011-01-21 12:26:12

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

因此,这一守则应适用于:

代码语言:javascript
复制
Node node = nodel.item(a);
if (node instanceof Element) {
    Element e = (Element) node;
    System.out.println(e.getAttribute("name");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4758685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档