我想从xml文件中获取这些元素,并将其用作java
中的字符串变量 <?xml version="1.0"?>
<componentProperties>
<component ID="SEC">
<properties>
<URL>https://retail/category</URL>
<Enable>True</Enable>
<Units>120</Units>
<Code>10110001</Code>
<OutPutFilePath>C:\new\tep\</OutPutFilePath>
</properties>
</component>
</componentProperties>
通过引用几个例子,我尝试使用DOM解析器,但没有工作。可能是代码错误
File file = new File("D:\\temp\\TestWifi\\DefaultSetting.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("properties");
Node fstNode = nodeLst.item(1);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList listurl = fstElmnt.getElementsByTagName("URL");
Element liurl = (Element) listurl.item(0);
NodeList URL = liurl.getChildNodes();
url.setText(((Node) URL.item(0)).getNodeValue());
答案 0 :(得分:1)
我这样做了
try{
InputStream is = getAssets().open("defaultsettings.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("properties");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
url.setText(url.getText()+ getValue("URL", element2));
strurl=getValue("URL", element2);
enbl.setText(enbl.getText()+ getValue("Enable", element2));
unit_.setText(timeout.getText()+ getValue("unit", element2));
code.setText(outpath.getText()+ getValue("code", element2));
code.setText(outpath.getText()+ getValue("OutPutFilePath", element2));
}
}
temp.setText(strurl);
} catch(Exception e) {
e.printStackTrace();
}