Объявление пространства имен XML fix
-
20-09-2019 - |
Вопрос
Я пытаюсь обнаружить / обойти это ошибка в элементах RSS.Это означает, что я должен найти неправильное объявление пространства имен и изменить его значение на правильное пространство имен.Например,:
xmlns:media="http://search.yahoo.com/mrss"
должно быть:
xmlns:media="http://search.yahoo.com/mrss/"
Как я могу добиться этого, учитывая org.w3c.Document?
Я имею в виду, что я выяснил, как получить все элементы определенного пространства имен:
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".
Возможно, вам придется немного подправить синтаксис, поскольку я пишу это без помощи компилятора.Кроме того, то, что вы получите, вероятно, не очень хорошо отформатировано (объявления пространства имен для многих элементов), но оно должно быть локально корректным.