XML命名空间的修复声明
-
20-09-2019 - |
题
我想detetct /变通这的bug RSS元素。 这意味着我必须找到一个错误的命名空间声明,并改变其 值,以正确的命名空间。 E.g:
xmlns:media="http://search.yahoo.com/mrss"
必须是:
xmlns:media="http://search.yahoo.com/mrss/"
如何achive给定一个org.w3c.Document?
我meanwile发现了如何获得一定的命名空间中的所有元素:
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expr = xpath.compile("//*[namespace-uri()='http://search.yahoo.com/mrss']");
Object result = expr.evaluate(d, XPathConstants.NODESET);
if (result != null) {
NodeList nodes = (NodeList) result;
for(int node=0;node<nodes.getLength();node++)
{
Node n = nodes.item(node);
this.log.warn("Found old mediaRSS namespace declaration: "+n.getTextContent());
}
}
所以现在我必须找出如何通过JAXP改变一个节点的命名空间。
解决方案 2
只是为了完整性的缘故:
Java代码:
Document d = out.outputW3CDom(converted);
DOMSource oldDocument = new DOMSource(d);
DOMResult newDocument = new DOMResult();
TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xsltsource = new StreamSource(
getStream(MEDIA_RSS_TRANSFORM_XSL));
Transformer transformer = tf.newTransformer(xsltsource);
transformer.transform(oldDocument, newDocument);
private InputStream getStream(String fileName) {
InputStream xslStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/" + fileName);
if (xslStream == null) {
xslStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(fileName);
}
return xslStream;
}
样式表:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--identity transform that will copy matched node/attribute to the output and apply templates for it's children and attached attributes-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|*|text()" />
</xsl:copy>
</xsl:template>
<!--Specialized template to match on elements with the incorrect namespace and generate a new element-->
<xsl:template match="//*[namespace-uri()='http://search.yahoo.com/mrss']">
<xsl:element name="{local-name()}" namespace="http://search.yahoo.com/mrss/" >
<xsl:apply-templates select="@*|*|text()" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
特别感谢马德斯·汉森对他的帮助用XSLT。
其他提示
您可以可能与XSLT做到这一点,像这样的规则:
<xsl:template match="media:*">
<xsl:element name="local-name()" namespace="http://search.yahoo.com/mrss/">
<xsl:apply-templates match="node()|@*"/>
</xsl:element>
</xsl:template>
其中媒体绑定到 “ http://search.yahoo.com/mrss ”。
您可能需要调整的语法了一点,因为我写这篇文章没有编译器的帮助。此外,你会得到大概不是非常格式良好的(在许多元素的命名空间的声明),但它应该是正确的locically
不隶属于 StackOverflow