在 Java 中使用命名空间创建 XML 文档 [英] Creating an XML document using namespaces in Java

查看:116
本文介绍了在 Java 中使用命名空间创建 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找可以构建使用名称空间的 XML 文档的示例 Java 代码.我似乎无法使用我的常规最喜欢的工具找到任何东西,所以希望有人能帮助我.p>

I am looking for example Java code that can construct an XML document that uses namespaces. I cannot seem to find anything using my normal favourite tool so was hoping someone may be able to help me out.

推荐答案

我不确定,你想做什么,但我使用 jdom 用于我的大多数 xml 问题,它支持命名空间(当然).

I am not sure, what you trying to do, but I use jdom for most of my xml-issues and it supports namespaces (of course).

代码:

Document doc = new Document();
Namespace sNS = Namespace.getNamespace("someNS", "someNamespace");
Element element = new Element("SomeElement", sNS);
element.setAttribute("someKey", "someValue", Namespace.getNamespace("someONS", "someOtherNamespace"));
Element element2 = new Element("SomeElement", Namespace.getNamespace("someNS", "someNamespace"));
element2.setAttribute("someKey", "someValue", sNS);
element.addContent(element2);
doc.addContent(element);

生成以下 xml:

<?xml version="1.0" encoding="UTF-8"?>
 <someNS:SomeElement xmlns:someNS="someNamespace" xmlns:someONS="someOtherNamespace"  someONS:someKey="someValue">
  <someNS:SomeElement someNS:someKey="someValue" />
 </someNS:SomeElement>

其中应该包含您需要的一切.希望对您有所帮助.

Which should contain everything you need. Hope that helps.

这篇关于在 Java 中使用命名空间创建 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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