【问题标题】:java xml retrieve named parameterjava xml检索命名参数
【发布时间】:2013-07-19 04:42:46
【问题描述】:
<root>
<program name="SomeProgramName">
    <params>
        <param name='name'>test</param>
        <param name='name2'>test2</param>
    </params>
</program>
</root>

我有上面的 xml 文档。我需要将 test 的值更改为新值

我在 xml 文档中读为

String xmlfile = "path\\to\\file.xml"
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlfile);

//get the params element
Node params = doc.getElementsByTagName("params").item(0);

//get a list of nodes in the params element
NodeList param = params.getChildNodes();

这就是我卡住的地方。我找不到通过“名称”设置参数之一的值的方法

我使用的是 java 1.7

【问题讨论】:

  • 我建议对它使用 XPath 查询。语法类似于/root/program/params/param[@name='name2']。有关 xpath 设置,请参阅 this question

标签: java xml


【解决方案1】:

您需要键入每个节点以键入Element 才能设置文本和属性。你可能想看看XPath,它简化了这样的事情。

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xmlfile = "src/forum17753835/file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlfile);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Element element = (Element) xpath.evaluate("/root/program/params/param[@name='name2']", doc, XPathConstants.NODE);
        System.out.println(element.getTextContent());
    }

}

【讨论】:

  • xpath 看起来很有趣。我会研究这个解决方案
【解决方案2】:
  NodeList params = doc.getElementsByTagName("param");
  for (int i = 0; i < params.getLength(); i++)
  {
     if (params.item(i).getAttributes().getNamedItem("name").getNodeValue().equals("name2"))
     {
        // do smth with element <param name='name2'>test2</param>
        // that is params.item(i) in current context
     }
  }

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2017-05-25
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多