Java 为 XML 节点赋值

标签 java xml dom

我正在尝试为空 XML 节点分配一个值,但它似乎不起作用。我的 XML 结构如下:

<createCustomer>
    <customerAttributes>
        <firstName></firstName>
        <lastName></lastName>
    </customerAttributes>
</createCustomer>

我正在尝试在以下代码中分配名字和姓氏:

private void createXML(Document skeleton, Map params) {
skeleton.getDocumentElement().normalize();

NodeList customerNodes = skeleton.getElementsByTagName("customerAttributes");

            for(int i=0; i<customerNodes.getLength(); i++) {
                NodeList children = customerNodes.item(i).getChildNodes();
                    for(int j=0; j<children.getLength(); j++) {
                        String childNode = children.item(j).getNodeName();
                            if(childNode.equalsIgnoreCase("firstName")){
                                children.item(j).setNodeValue(String.valueOf(params.get("fname")));
                                System.out.println(children.item(j));
                            }
                            else if (childNode.equalsIgnoreCase("lastName")){
                                children.item(j).setNodeValue(String.valueOf(params.get("sname")));
                                System.out.println(children.item(j));
                            }
                    }  
             }

     }
}

打印语句的输出是:

firstname: null surname: null

但我确信映射中的值是正确的,因为 print 语句输出预期的映射值。另外,如果我替换 params.get("string")使用硬编码字符串,我仍然得到输出:firstname: null 。该代码没有抛出任何异常。我也尝试过setTextContent但这也不起作用

最佳答案

您可以使用setTextContent(String):

NodeList customerNodes = skeleton.getElementsByTagName("customerAttributes");
for (int i = 0; i < customerNodes.getLength(); i++) {
    NodeList children = customerNodes.item(i).getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
        String childNode = children.item(j).getNodeName();
        if (childNode.equalsIgnoreCase("firstName")) {
            children.item(j).setTextContent(String.valueOf(params.get("fname")));
        }
        else if (childNode.equalsIgnoreCase("lastName")) {
            children.item(j).setTextContent(String.valueOf(params.get("sname")));
        }
    }  
}

编辑:

它有效,这是显示结果的完整示例。

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class Foo {
    public static void main(String[] args) throws Exception {
        // --------- LOAD XML
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader("<createCustomer>\r\n" + 
                "    <customerAttributes>\r\n" + 
                "        <firstName></firstName>\r\n" + 
                "        <lastName></lastName>\r\n" + 
                "    </customerAttributes>\r\n" + 
                "</createCustomer>")));

        // --------- PROCESS
        NodeList customerNodes = doc.getElementsByTagName("customerAttributes");

        for (int i = 0; i < customerNodes.getLength(); i++) {
            NodeList children = customerNodes.item(i).getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                String childNode = children.item(j).getNodeName();
                if (childNode.equalsIgnoreCase("firstName")) {
                    children.item(j).setTextContent(String.valueOf("John"));
                }
                else if (childNode.equalsIgnoreCase("lastName")) {
                    children.item(j).setTextContent(String.valueOf("Doe"));
                }
            }  
        }

        // --------- OUTPUT
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        System.out.println(writer.getBuffer().toString());
    }
}

它确实输出:

<createCustomer>
    <customerAttributes>
        <firstName>John</firstName>
        <lastName>Doe</lastName>
    </customerAttributes>
</createCustomer>

关于Java 为 XML 节点赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20682263/

相关文章:

java - 如何将 flush() 用于 PrintWriter

java - 从另一个类访问对象数组

java - JSR 303 : Is it possible to validate whole graph automatically?

javascript - 在 JavaScript (DOM) 中处理 XML 命名空间

java - 无法解析符号fragment_main

Python - for循环仅输出最后一次迭代

kSOAP 中复杂类型的 XML/SOAP 属性

javascript - 为什么 Webkit 不能正确重绘我的网页?

javascript - Chrome 扩展程序将外部 javascript 添加到当前页面的 html

xml - XSL-FO 页码 2a、2b