英文:
Java xml parse getElementById returns null
问题
因此,某种原因,当在Java中解析XML时,我无法使用getElementById("ID_VALUE")
,但在Android中一切正常,而在常规Java中却不行。当我尝试解析XML时,该元素返回null。我看到了一些关于可能使用模式的想法,但是我不知道如何做。
public void getFromID() throws Exception {
File file = new File("/home/nodes.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
//document.getDocumentElement().normalize();
System.out.println(id);
Element element = document.getElementById(id);
System.out.println(element);
//Element element = (Element) document.getElementsByTagName("node").item(0);
//System.out.println(element.getNodeValue());
this.address = element.getAttribute("address");
this.port = Integer.parseInt(element.getAttribute("port"));
this.base64Key = element.getAttribute("key");
System.out.println(address);
System.out.println(port);
System.out.println(base64Key);
}
public void save() throws Exception {
File file = new File("/home/nodes.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("nodes");
Element enode = document.createElement("node");
enode.setAttribute("id", id);
enode.setAttribute("address", address);
enode.setAttribute("port", port + "");
enode.setAttribute("key", base64Key);
//enode.setIdAttributeNS(null, "id", true);
enode.setIdAttribute("id", true);
root.appendChild(enode);
document.appendChild(root);
//document.getDocumentElement().normalize();
document.setXmlStandalone(true);
Transformer tfactory = TransformerFactory.newInstance().newTransformer();
tfactory.setOutputProperty(OutputKeys.METHOD, "xml");
tfactory.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tfactory.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));
}
XML
<?xml version="1.0" encoding="UTF-8"?><nodes><node address="127.0.0.1" id="123123" key="ASDASDASD" port="8000"/></nodes>
英文:
So for some reason when parsing XML in java I can't getElementById("ID_VALUE")
however this all works fine within android, but not with regular java. When I attempt to parse the XML I just get null for the element. I've seen a couple thoughts on maybe using a schema, however I have no idea how to do that.
Java
public void getFromID()throws Exception {
File file = new File("/home/nodes.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
//document.getDocumentElement().normalize();
System.out.println(id);
Element element = document.getElementById(id);
System.out.println(element);
//Element element = (Element) document.getElementsByTagName("node").item(0);
//System.out.println(element.getNodeValue());
this.address = element.getAttribute("address");
this.port = Integer.parseInt(element.getAttribute("port"));
this.base64Key = element.getAttribute("key");
System.out.println(address);
System.out.println(port);
System.out.println(base64Key);
}
public void save()throws Exception {
File file = new File("/home/nodes.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("nodes");
Element enode = document.createElement("node");
enode.setAttribute("id", id);
enode.setAttribute("address", address);
enode.setAttribute("port", port+"");
enode.setAttribute("key", base64Key);
//enode.setIdAttributeNS(null, "id", true);
enode.setIdAttribute("id", true);
root.appendChild(enode);
document.appendChild(root);
//document.getDocumentElement().normalize();
document.setXmlStandalone(true);
Transformer tfactory = TransformerFactory.newInstance().newTransformer();
tfactory.setOutputProperty(OutputKeys.METHOD, "xml");
tfactory.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tfactory.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));
}
XML
<?xml version="1.0" encoding="UTF-8"?><nodes><node address="127.0.0.1" id="123123" key="ASDASDASD" port="8000"/></nodes>
答案1
得分: 1
由于您了解您的XML文件的结构,我建议您使用JAXB(Java XML绑定)API,而不是解析原始XML,而是将XML文件映射到您预定义的POJO。将依赖项添加到您的pom.xml中:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
然后,创建您的POJO类(假设为Nodes.java
和Node.java
)并根据您的XML文件对字段进行注释。
@XmlRootElement(name = "nodes")
public class Nodes {
@XmlElement(name = "node")
private Node node;
public Node getNode() {
return node;
}
}
public class Node {
@XmlAttribute(name="address")
private String address;
@XmlAttribute(name="id")
private String id;
@XmlAttribute(name="key")
private String key;
@XmlAttribute(name="port")
private String port;
public String getAddress() {return address;}
public String getId() {return id;}
public String getKey() {return key;}
public String getPort() {return port;}
}
因此,使用JAXB Unmarshaller解析XML文件与您的类(注意:这里我假设XML文件加载到String xmlString
中):
jaxbContext = JAXBContext.newInstance(Nodes.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Nodes nodes = (Nodes) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
在这一点上,整个XML都加载到了Nodes nodes
实例中,所以您可以使用nodes.getNode().getId()
来检索您的值(以及所有其他值)。
一般注意:只有当您真正不知道XML文件是如何构建的并且需要探索它时,才应该使用通用XML解析器。如果您了解XML(即您知道它代表什么对象),那么最好将其表示为这样。
英文:
Since you know the structure of your XML file, I suggest you to use JAXB (JAva Xml Binding) API in order not to parse raw XML but rather map the XML file to a POJO you have predefined.
Add the dependency to your pom.xml:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
Then, create your POJO classes (let's say Nodes.java
and Node.java
) and annotate the fields according to your XML file.
@XmlRootElement(name = "nodes")
public class Nodes {
@XmlElement(name = "node")
private Node node;
public Node getNode() {
return node;
}
}
public class Node {
@XmlAttribute(name="address")
private String address;
@XmlAttribute(name="id")
private String id;
@XmlAttribute(name="key")
private String key;
@XmlAttribute(name="port")
private String port;
public String getAddress() {return address;}
public String getId() {return id;}
public String getKey() {return key;}
public String getPort() {return port;}
}
Hence, parse the XML file against your class using the JAXB Unmarshaller (note: here I assume the XML file is loaded into a String xmlString
):
jaxbContext = JAXBContext.newInstance(Nodes.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Nodes nodes = (Nodes) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
At this point, your whole XML is loaded into the instance Nodes nodes
so you can just do nodes.getNode().getId()
to retrieve your value (as well as all the other values).
General note: you should use the general Xml parser just when you really don't know how the XML file is done and you need to explore it. If you know the XML (i.e. you know what object it represents), then it's better to represent it as such.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论