java dom getTextContent() 问题

2023-12-08

当我尝试访问我的 xml 数据时doGet我的 servlet 的方法,它只输出直到空白的值,包括整个值。

XML 文件:

<RealEstate>
    <Property>
            <Type>Apartment</Type>
            <Bedrooms>2</Bedrooms>
            <Bathrooms>2</Bathrooms>
            <Suburb>Bondi Junction</Suburb>
            <Rent>1000</Rent>
    </Property>
</RealEstate>

然后我从 Java Servlet 中调用 SuburbdoGet:

Node suburb1 = doc.getElementsByTagName("Suburb").item(i);
out.println("<tr><td>Suburb</td>" + "<td>"+suburb1.getTextContent()+"</td></tr>");

它只输出“Bondi”而不是“Bondi Junction”

有人知道为什么吗?


我用你的xml尝试过你的代码,它为我打印出整个文本内容,非常奇怪。无论如何,Node#getTextContext方法返回当前节点及其后代的文本内容。 我建议你使用node.getFirstChild().getNodeValue(),它打印出您的节点的文本内容,而不是其后代。另一种方法是迭代 Suburbs 节点的子节点。 你也应该看看here.

这是我的主要内容,它使用两者打印出相同的文本两次getFirstChild().getNodeValue() and getChildNodes().item(i).getNodeValue():

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException  {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(new File("dom.xml"));

    NodeList nodeList = doc.getElementsByTagName("Suburb");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.hasChildNodes()) {

            System.out.println("<tr><td>Suburb</td>" + "<td>"+node.getFirstChild().getNodeValue()+"</td></tr>");

            NodeList textNodeList = node.getChildNodes();
            StringBuilder textBuilder = new StringBuilder();
            for (int j = 0; j < textNodeList.getLength(); j++) {
                Node textNode = textNodeList.item(j);
                if (textNode.getNodeType() == Node.TEXT_NODE) {
                    textBuilder.append(textNode.getNodeValue());
                }
            }
            System.out.println("<tr><td>Suburb</td>" + "<td>" + textBuilder.toString() + "</td></tr>");
        }
    }
}

这是我的 xml 输出:

<tr><td>Suburb</td><td>Bondi Junction</td></tr>
<tr><td>Suburb</td><td>Bondi Junction</td></tr>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java dom getTextContent() 问题 的相关文章

随机推荐