如何使用dom在XML文件中附加元素? [英] How to append element in a XML file using dom?

查看:111
本文介绍了如何使用dom在XML文件中附加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的XML文件如下:

<Messages>
    <Contact Name="Robin" Number="8775454554">
        <Message Date="24 Jan 2012" Time="04:04">this is report1</Message>
    </Contact>
    <Contact Name="Tobin" Number="546456456">
        <Message Date="24 Jan 2012" Time="04:04">this is report2</Message>
    </Contact>
<Messages>

我需要检查Contact元素的 Number属性是否等于 somenumber,以及是的,我需要在Contact元素内再插入一个Message元素。

I need to check whether the 'Number' attribute of Contact element is equal to 'somenumber' and if it is, I'm required to insert one more Message element inside Contact element.

如何使用DOM来实现?以及使用DOM的缺点是什么?

How can it be achieved using DOM? And what are the drawbacks of using DOM?

推荐答案

使用DOM的主要缺点是必须将整个模型加载到一次存储,而不是只解析文档,而是可以一次限制存储在内存中的数据。在处理非常大的XML文档之前,这当然不是真正的问题。

The main drawback to using a DOM is it's necessary to load the whole model into memory at once, rather than if your simply parsing the document, you can limit the data you keep in memory at one point. This of course isn't really an issue until your processing very large XML documents.

至于处理方面,应该执行以下操作:

As for the processing side of things, something like the following should work:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(is);
NodeList contacts = dom.getElementsByTagName("Contact");
for(int i = 0; i < contacts.getLength(); i++) {
    Element contact = (Element) contacts.item(i);
    String contactNumber = contact.getAttribute("Number");
    if(contactNumber.equals(somenumber)) {
        Element newMessage = dom.createElement("Message");
        // Configure the message element
        contact.appendChild(newMessage);
    }
}

这篇关于如何使用dom在XML文件中附加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆