为什么这个java代码没有正确解析我的Xml?

时间:2021-10-10 20:19:47

I've written class to parse some xml into an object and it's not working correctly, when I try and get the value of a node I get a null rather than the contents of the node.

我已经编写了一个类来解析一些xml到一个对象并且它无法正常工作,当我尝试获取一个节点的值时,我得到的是null而不是节点的内容。

Here is a simplified version of my class that just does the xml parsing of a single node:

这是我的类的简化版本,它只对单个节点进行xml解析:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlReaderCutDown {

    private static Logger logger = Logger.getLogger(CtiButtonsXmlReader.class);

    public static void testXml(String confFile){
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(confFile));
            doc.getDocumentElement().normalize();
            if (logger.isDebugEnabled()){
                logger.debug("The root element is " + doc.getDocumentElement().getNodeName());
            }

            NodeList rows =  doc.getElementsByTagName("row");

            NodeList topRowButtons = ((Element)rows.item(0)).getElementsByTagName("button");
            logger.debug("Top row has " +topRowButtons.getLength() + " items.");
            Node buttonNode = topRowButtons.item(0);

            NodeList nodeList = ((Element)buttonNode).getElementsByTagName("id");
            logger.debug("Node list count for "+ "id" + " = " + nodeList.getLength());
            Element element = (Element)nodeList.item(0);
            String xx = element.getNodeValue();
            logger.debug(xx);
            String elementValue = ((Node)element).getNodeValue();
            if (elementValue != null) {
                elementValue = elementValue.trim();
            }
            else {
                logger.debug("Value was null");
            }
            logger.debug("Node id = "+ elementValue);

        } catch (ParserConfigurationException e) {

            logger.fatal(e.toString(),e);
        } catch (SAXException e) {
            logger.fatal(e.toString(),e);
        } catch (IOException e) {
            logger.fatal(e.toString(),e);
        } catch (Exception e) {
            logger.fatal(e.toString(),e);
        }

    }


    public static void main(String[] args){
        DOMConfigurator.configure("log4j.xml");

        testXml("test.xml");
    }
}

And here is a stripped down version of my xml file:

这是我的xml文件的精简版本:

<?xml version="1.0"?>
<root>
    <row>
        <button>
            <id>this is an id</id>
            <action>action</action>
            <image-src>../images/img.png</image-src>
            <alt-text>alt txt</alt-text>
            <tool-tip>Tool tip</tool-tip>
        </button>
    </row>
</root>

This is what the logging statments output:

这是日志记录语句输出的内容:

DEBUG XmlReaderCutDown - The root element is root

DEBUG XmlReaderCutDown - 根元素是root

DEBUG XmlReaderCutDown - Top row has 1 items.

DEBUG XmlReaderCutDown - 顶行有1个项目。

DEBUG XmlReaderCutDown - Node list count for id = 1

DEBUG XmlReaderCutDown - id = 1的节点列表计数

DEBUG XmlReaderCutDown -

DEBUG XmlReaderCutDown -

DEBUG XmlReaderCutDown - Value was null

DEBUG XmlReaderCutDown - 值为null

DEBUG XmlReaderCutDown - Node id = null

DEBUG XmlReaderCutDown - 节点id = null

Why isn't it getting the text in the xml node?

为什么不在xml节点中获取文本?

I'm running using JDK 1.6_10

我正在使用JDK 1.6_10运行

3 个解决方案

#1


Because the element you get is the parent element of the text one, containing the text you need. To access the text of this element, you shall use getTextContent instead of getNodeValue.

因为您获得的元素是文本的父元素,包含您需要的文本。要访问此元素的文本,您应使用getTextContent而不是getNodeValue。

For more information, see the table in the Node javadoc.

有关更多信息,请参阅Node javadoc中的表。

#2


See http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html . Element.getNodeValue() always returns null. You should use Element.getTextContent()

请参阅http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html。 Element.getNodeValue()始终返回null。你应该使用Element.getTextContent()

#3


Consider using XPath as an alternative to manually walking nodes:

考虑使用XPath作为手动移动节点的替代方法:

  public static void testXml(String confFile)
      throws XPathExpressionException {
    XPathFactory xpFactory = XPathFactory.newInstance();
    XPath xpath = xpFactory.newXPath();

    NodeList rows = (NodeList) xpath.evaluate("root/row",
        new InputSource(confFile), XPathConstants.NODESET);

    for (int i = 0; i < rows.getLength(); i++) {
      Node row = rows.item(i);
      String id = xpath.evaluate("button/id", row);
      System.out.println("id=" + id);
    }
  }

  public static void main(String[] args)
      throws XPathExpressionException {
    testXml("test.xml");
  }

#1


Because the element you get is the parent element of the text one, containing the text you need. To access the text of this element, you shall use getTextContent instead of getNodeValue.

因为您获得的元素是文本的父元素,包含您需要的文本。要访问此元素的文本,您应使用getTextContent而不是getNodeValue。

For more information, see the table in the Node javadoc.

有关更多信息,请参阅Node javadoc中的表。

#2


See http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html . Element.getNodeValue() always returns null. You should use Element.getTextContent()

请参阅http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html。 Element.getNodeValue()始终返回null。你应该使用Element.getTextContent()

#3


Consider using XPath as an alternative to manually walking nodes:

考虑使用XPath作为手动移动节点的替代方法:

  public static void testXml(String confFile)
      throws XPathExpressionException {
    XPathFactory xpFactory = XPathFactory.newInstance();
    XPath xpath = xpFactory.newXPath();

    NodeList rows = (NodeList) xpath.evaluate("root/row",
        new InputSource(confFile), XPathConstants.NODESET);

    for (int i = 0; i < rows.getLength(); i++) {
      Node row = rows.item(i);
      String id = xpath.evaluate("button/id", row);
      System.out.println("id=" + id);
    }
  }

  public static void main(String[] args)
      throws XPathExpressionException {
    testXml("test.xml");
  }