Java为XML节点分配值

时间:2013-12-19 12:51:28

标签: 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));
                            }
                    }  
             }

     }
}

print语句的输出是:

firstname: null surname: null

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

1 个答案:

答案 0 :(得分:1)

您可以使用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>