使用dom4j添加名称空间和名称空间前缀 [英] adding namespace and namespace prefix using dom4j

查看:1229
本文介绍了使用dom4j添加名称空间和名称空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用dom4j更新一个xml,如下所示.

i am updating one xml using dom4j as below.

    SAXReader reader = new SAXReader();
document = reader.read( xmlFileName );

但是它从元素中删除了所有名称空间,因此想手动添加,但是当我尝试以下代码时它不起作用.

but it removes all namespaces from the elements so wanna add manually but it does not work when i tried the following code.

    Element e1 = root.addElement("jmsProducer");   
    e1.addNamespace("AEService", "http://www.tibco.com/xmlns/aemeta/services/2002");

我的xml看起来像

    <AEService:jmsProducer objectType="endpoint.JMSPublisher" name="Pub1EndPoint">  
    <AEService:wireFormat>aeXml</AEService:wireFormat>

泡沫看起来像

    <AEService:jmsProducer xmlns:AEService="http://www.tibco.com/xmlns/aemeta/services   /2002" objectType="endpoint.JMSPublisher" name="Pub1EndPoint">
    <AEService:wireFormat>aeXml</AEService:wireFormat>

高度重视任何帮助.猛撞了两天,尝试使用documentfactory方法仍然没有用.

any help is highly appriciated. banging on this for two days tried using documentfactory method still no use.

推荐答案

我意识到这是一个旧线程,并且在编写答案时dom4j可能没有足够的命名空间功能,但现在看来dom4j能够使用我正在使用的版本(1.6.1)轻松完成此操作.我来到这里寻求有关如何使用dom4j构建可识别名称空间的XML的帮助,以发布Java代码(以在原始文章中构建XML代码段),以防它对某人有所帮助.

I realize that this is an old thread, and dom4j may not have had adequate namespace capabilities at the time the answers were written, but it looks like dom4j is now able to accomplish this quite easily with the version I am using (1.6.1). I came here looking for help on how to build a namespace aware XML with dom4j, posting my Java code (to build the XML snippet in the original post) in case it helps someone.

这是构建它的Java代码.

Here is the Java code to build it.

Document xmldoc = DocumentHelper.createDocument();
Namespace aeServiceNs = new Namespace("AEService",
  "http://www.tibco.com/xmlns/aemeta/services/2002");
Element root = xmldoc.addElement(new QName("jmsProducer", aeServiceNs))
                     .addAttribute("objectType", "endpoint.JMSPublisher")
                     .addAttribute("name", "Pub1EndPoint");
Element wireformat = root.addElement(new QName("wireFormat", aeServiceNs))
                         .setText("aeXml");
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
XMLWriter xmlwriter = new XMLWriter(System.out, outputFormat);
xmlwriter.write(xmldoc);

产生以下输出:

<?xml version="1.0" encoding="UTF-8"?>

<AEService:jmsProducer 
    xmlns:AEService="http://www.tibco.com/xmlns/aemeta/services/2002" 
    objectType="endpoint.JMSPublisher" name="Pub1EndPoint">
  <AEService:wireFormat>aeXml</AEService:wireFormat>
</AEService:jmsProducer>

希望这会有所帮助.

这篇关于使用dom4j添加名称空间和名称空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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