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

为什么这个java代码不能正确解析我的Xml?,java,xml,dom,Java,Xml,Dom,我编写了一个类来将一些xml解析为一个对象,但它无法正常工作,当我尝试获取节点的值时,得到的是null,而不是节点的内容 下面是我的类的简化版本,它只对单个节点进行xml解析: import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderF

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

下面是我的类的简化版本,它只对单个节点进行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");
    }
}
下面是我的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>

这是一个身份证
行动
../images/img.png
alt txt
刀尖
这是记录状态的输出:

调试XmlReaderCutDown-根元素为root

调试XmlReaderCutDown-顶行有1项

调试XmlReaderCutDown-id为1的节点列表计数

调试XmlReaderCutDown-

调试XmlReaderCutDown-值为null

调试XmlReaderCutton-节点id=null

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


我使用JDK1.6_10运行,因为您得到的元素是文本1的父元素,包含您需要的文本。要访问此元素的文本,应使用而不是getNodeValue

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

请参阅。getNodeValue()总是返回null。您应该使用Element.getTextContent()

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

  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");
  }
publicstaticvoidtestxml(字符串文件)
抛出XPathExpressionException{
XPathFactory xpFactory=XPathFactory.newInstance();
XPath=xpFactory.newXPath();
NodeList rows=(NodeList)xpath.evaluate(“根/行”,
新的输入源(confFile),XPathConstants.NODESET);
对于(int i=0;i
注意:如果您想试用但没有log4j,则可以使用System.out.println()替换日志状态;谢谢,这很有魅力,但有一个问题是,当这个页面上的代码使用节点值时,为什么会起作用?因为它们得到了相关元素的第一个子元素,即文本节点。全局而言,它与getTextContent的功能相同,只是在getTextContent情况下更安全。您可以在文本节点上使用nodeValue()。