java用dom更新xml的问题,怎么在子节点下添加节点?

yeyerl 2012-11-21 11:03:00
有原始xml如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student>
<name sn="03" sn2="0322"/>
</student>
</students>

我想要得到修改后的结果为:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student>
<name sn="03" sn2="0322"/>
<name sn="04" sn2="0422"/>
</student>
</students>


我的代码为:

public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("D:/students.xml");
Element eltName = doc.createElement("name");

Attr attr = doc.createAttribute("sn");
attr.setValue("04");
Attr attr2 = doc.createAttribute("sn2");
attr2.setValue("0422");

eltName.setAttributeNode(attr);
eltName.setAttributeNode(attr2);

Element eltRoot=doc.getDocumentElement();
eltRoot.appendChild(eltName);
doc2XmlFile(doc, "D:/students.xml");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 将Document对象修改后写入到xml里面
* @param document Document对象
* @param filename xml文件路径
* @return
*/
public boolean doc2XmlFile(Document document, String filename) {
boolean flag = true;
try {
/** 将document中的内容写入文件中 */
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
/** 编码 */
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(filename));
transformer.transform(source, result);
} catch (Exception ex) {
flag = false;
System.out.println("更新" + filename + "出错:" + ex);
log.error("更新" + filename + "出错:" + ex);
ex.printStackTrace();
}
return flag;
}




这样得到的结果为:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student>
<name sn="03" sn2="0322"/>
</student>
<name sn="04" sn2="0422"/>
</students>


弄了一天了也没能把添加的name节点放到student节点下面,请教各位大侠了!
...全文
440 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
yeyerl 2012-11-22
  • 打赏
  • 举报
回复
引用 1 楼 ibanezz 的回复:
你组织文档时候写的代码是这样的: Java code?12 Element eltRoot=doc.getDocumentElement();//获取根节点eltRoot.appendChild(eltName);//将新的节点拼接到根节点 所以你得到的结果必然是这样: XML/HTML code?1234567<?xml version="1.0" encodin……
http://www.iteye.com/problems/90441 我在这里也提问了,这位大神的也简单,您的我也测试了,也可以,非常感谢!
ibanezz 2012-11-22
  • 打赏
  • 举报
回复
你组织文档时候写的代码是这样的:
 Element eltRoot=doc.getDocumentElement();//获取根节点
eltRoot.appendChild(eltName);//将新的节点拼接到根节点
所以你得到的结果必然是这样:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  <students>
    <student>
      <name sn="03" sn2="0322"/>
    </student>
    <name sn="04" sn2="0422"/>
  </students>
这样修改可以实现你要的效果:
            Element eltRoot=doc.getDocumentElement();
            
            NodeList list = eltRoot.getChildNodes();
            if (list != null) {
            	for (int i = 0; i < list.getLength(); i++) {
            		if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
            			list.item(i).appendChild(eltName);
            		}
            	}
			}
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析的XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个节点(指定节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取节点的那个父节点 * @param childName 要获取的节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的节点 * @throws Exception 子结点不存在或有多个符合条件的节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

50,503

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧