Java XML解析getElementById返回null。

huangapple go评论81阅读模式
英文:

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(&quot;ID_VALUE&quot;) 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(&quot;/home/nodes.xml&quot;);
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(&quot;node&quot;).item(0);
//System.out.println(element.getNodeValue());
this.address = element.getAttribute(&quot;address&quot;);
this.port = Integer.parseInt(element.getAttribute(&quot;port&quot;));
this.base64Key = element.getAttribute(&quot;key&quot;);
System.out.println(address);
System.out.println(port);
System.out.println(base64Key);
}
public void save()throws Exception {
File file = new File(&quot;/home/nodes.xml&quot;);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement(&quot;nodes&quot;);
Element enode = document.createElement(&quot;node&quot;);
enode.setAttribute(&quot;id&quot;, id);
enode.setAttribute(&quot;address&quot;, address);
enode.setAttribute(&quot;port&quot;, port+&quot;&quot;);
enode.setAttribute(&quot;key&quot;, base64Key);
//enode.setIdAttributeNS(null, &quot;id&quot;, true);
enode.setIdAttribute(&quot;id&quot;, true);
root.appendChild(enode);
document.appendChild(root);
//document.getDocumentElement().normalize();
document.setXmlStandalone(true);
Transformer tfactory = TransformerFactory.newInstance().newTransformer();
tfactory.setOutputProperty(OutputKeys.METHOD, &quot;xml&quot;);
tfactory.setOutputProperty(OutputKeys.ENCODING, &quot;UTF-8&quot;);
tfactory.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));
}

XML

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;nodes&gt;&lt;node address=&quot;127.0.0.1&quot; id=&quot;123123&quot; key=&quot;ASDASDASD&quot; port=&quot;8000&quot;/&gt;&lt;/nodes&gt;

答案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.javaNode.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:

&lt;dependency&gt;
&lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
&lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
&lt;version&gt;2.3.0&lt;/version&gt;
&lt;/dependency&gt;

Then, create your POJO classes (let's say Nodes.java and Node.java) and annotate the fields according to your XML file.

@XmlRootElement(name = &quot;nodes&quot;)
public class Nodes {
@XmlElement(name = &quot;node&quot;)
private Node node;            
public Node getNode() {
return node; 
}
}

public class Node {
@XmlAttribute(name=&quot;address&quot;)
private String address;
@XmlAttribute(name=&quot;id&quot;)
private String id;
@XmlAttribute(name=&quot;key&quot;)
private String key;
@XmlAttribute(name=&quot;port&quot;)
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.

huangapple
  • 本文由 发表于 2020年7月22日 06:24:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63023999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定