尽管描述看起来很长,但它实际上非常简单 .
我需要什么
我有以下xml文档
<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:atom="http://www.w3.org/2005/Atom" type="application/atom+xml;type=feed">
<atom:link rel="self" href="http://hostname/thirdparty/playlist"/>
<atom:id>vuter id</atom:id>
<atom:title>Untitled</atom:title>
<opensearch:totalResults>249</opensearch:totalResults>
<opensearch:startIndex>1</opensearch:startIndex>
<opensearch:itemsPerPage>249</opensearch:itemsPerPage>
<atom:entry type="application/atom+xml;type=entry">
<atom:id>12345678</atom:id>
<atom:title>Playlist example 1</atom:title>
<atom:link rel="self" type="application/atom+xml;type=entry" href="http://hostname/thirdparty/playlist/2101211130000011141"/>
<dcterms:identifier>2101211130000011141</dcterms:identifier>
</atom:entry>
<atom:entry type="application/atom+xml;type=entry">
<atom:id>12345678</atom:id>
<atom:title>Playlist example 2</atom:title>
<atom:link rel="self" type="application/atom+xml;type=entry" href="http://hostname/thirdparty/playlist/2101211090000000341"/>
<dcterms:identifier>2101211090000000341</dcterms:identifier>
</atom:entry>
</atom:feed>
请注意,xml基本上包含三个名称空间
-
dcterms :http://purl.org/dc/terms/
-
opensearch :http://a9.com/-/spec/opensearch/1.1/
现在我需要生成一个 atom:entry 节点的另一个xml文档 . 如下
<atom:entry type="application/atom+xml;type=entry" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:atom="http://www.w3.org/2005/Atom">
<atom:id>12345678</atom:id>
<atom:title>Playlist example 1</atom:title>
<atom:link rel="self" type="application/atom+xml;type=entry" href="http://hostname/thirdparty/playlist/2101211130000011141"/>
<dcterms:identifier>2101211130000011141</dcterms:identifier>
</atom:entry>
我得到了什么
我正在使用XOM,到目前为止我已尝试过
Element rootElem = new Builder().build(ins).getRootElement();
xc = XPathContext.makeNamespaceContext(rootElem);
Element firstEntry = (Element) rootElem.query("atom:entry", xc).get(0);
Document doc = new Document((Element)firstEntry.copy());
System.out.println(doc.toXML());
我只使用一个名称空间声明来跟踪xml . 如下 .
<?xml version="1.0"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" type="application/atom+xml;type=entry">
<atom:id>12345678</atom:id>
<atom:title>Playlist example 1</atom:title>
<atom:link rel="self" type="application/atom+xml;type=entry" href="http://hostname/thirdparty/playlist/2101211130000011141" />
<dcterms:identifier xmlns:dcterms="http://purl.org/dc/terms/">2101211130000011141</dcterms:identifier>
</atom:entry>
问题
它仅包含 Atom 名称空间:(因此它不是有效的XML . 因为它有一个子节点 dcterms:identifier ,其名称空间缺失 .
我需要帮助才能摆脱这个问题 . 期待任何帮助 .
2 回答
没问题 . dcterms命名空间在需要的地方声明:在dcterms:identifier标签中
事实上,你期望的xml和你得到的xml是一样的 . 名称空间未在同一位置声明的事实不会影响xml内容的含义 .
======= UPDATE ========
我建议解决真正的问题,即你的系统不接受有效的xmls(或者它没有正确解释它们) . 为了解决您的情况,请尝试以下代码:
基本上,上面的代码遍历所有子代,标识命名空间并将其作为名称空间声明添加到根目录 . 我尝试过并且工作过 . 我希望它能解决你的问题
你要