我试图从java文件修改xml文件的某些参数。在所有帖子中,我发现人们修改这些参数,通过标签名称进行搜索,但在我的情况下,它不起作用。
我的xml文件的一个例子是:
<?xml version="1.0" encoding="UTF-8"?>
<comp>
<params>
<param name="id">1</param>
<param name="type">aaaa</param>
<param name="bus">123</param>
</params>
</comp>
我如何通过&#34; name&#34;?
访问参数最后我在java中的代码是:
public void modifyXml(){
String path = "C:\\Workspace\\Project\\data.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(path);
Node comp = doc.getFirstChild();
Node params = doc.getElementsByTagName("params").item(0);
loadParams(params);
}
private void loadParams(Node params) {
NodeList list = params.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node url = list.item(i);
String nodeName = url.getNodeName();
NamedNodeMap attributes = url.getAttributes();
//System.out.println(attributes.item(i));
if (nodeName.equalsIgnoreCase("param") && url.getFirstChild()!=null) {
ServerProperties.getExternalParamsMap().put(attributes.getNamedItem("name").getNodeValue(), url.getFirstChild().getNodeValue());
System.out.println((String) url.getFirstChild().getNodeName());
System.out.println(url.getFirstChild().getNodeValue());
}
}
}
它打印节点的值,但不打印参数名称。参数名称如下所示:&#34; #text&#34;
谢谢!
此致!!
Eric P。
答案 0 :(得分:1)
你应该使用XPath来简化编码......下面是基于XPath和vtd-xml的代码。
lapply(data_a, function(x){ length(which(x==0))/length(x)})
答案 1 :(得分:0)
现在它对我有用:
String path = "C:\\Workspace\\Project\\data.xml";
File file = new File(path);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
javax.xml.parsers.DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Node id = (Node) document.getElementsByTagName("param").item(0);
id.setTextContent("xxxxxxx");
System.out.println(usr.getTextContent());
这将修改“id”参数