如何在xml中编写无根列表 [英] How to write rootless list in xml

查看:36
本文介绍了如何在xml中编写无根列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用以下格式写一个xml文件:

I want to write an xml file using the following format:

<root>
    <date> 9:51 AM 10/10/2012 </date>
    <responseTime> 1.20</responseTime>
    <employee>
        <name> Mohammad</name>
    </employee>
    <employee>
        <name> Ali</name>
    </employee>
    <employee>
        <name> Mostafa</name>
    </employee>
    <employee>
        <name> Mahmoud</name>
    </employee>
</root>

我可以使用 DOM 编写它吗?还是我应该手写?

Can I wrote it using DOM? or should I write it by hand?

(问题在于employee节点是一个没有直接父节点的序列来扭曲所有没有dateresponseTime元素的employee元素)

(The problem in that the employee node is a sequence without a direct parent node to warp all employee elements without date and responseTime elements)

推荐答案

我不认为用 DOM 做这件事有什么问题.

I don't see the problem with doing it with DOM.

代码:

public static void main(String[] args) throws ParserConfigurationException, IOException, TransformerException
{
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element root = document.createElement("root");
    document.appendChild(root);

    Element emp1 = document.createElement("employee");
    Element emp1name = document.createElement("name");
    emp1name.setTextContent("Mohammad");
    emp1.appendChild(emp1name);
    Element emp2 = document.createElement("employee");
    Element emp2name = document.createElement("name");
    emp2name.setTextContent("Ali");
    emp2.appendChild(emp2name);

    root.appendChild(emp1);
    root.appendChild(emp2);

    printDocument(document, System.out);
}

输出:

<root>
    <employee>
        <name>Mohammad</name>
    </employee>
    <employee>
        <name>Ali</name>
    </employee>
</root>

您可以在此SO Answer中查看printDocument的源代码.

You can see the source code for printDocument in this SO Answer.

可以在此处找到完整的源代码.

Full source code can be found here.

这篇关于如何在xml中编写无根列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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