how to remove the namespaces from the Element

风流意气都作罢 提交于 2019-12-11 09:39:55

问题


I am working with org.w3c.xml java library and encountering a few difficulties performing a few tasks:

  1. I have an Element object; how can I remove namespaces from it and the predecessors?
  2. How can I create a Document without the namespaces? I have tried

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(false);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("C:/Temp/XMLFiles/"+fileName+".xml"));
    

    Although it looks promising, it does not really work. I am still getting the doc with namespaces.

  3. How do I create a document from an Element?

    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    doc.adoptNode(dataDefinition);
    

    where dataDefinition is an element, but it didn't work; what am I doing wrong?


回答1:


Try transforming it with the following XSL:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<xsl:template match="/|comment()|processing-instruction()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>
</xsl:stylesheet>

Transformer xformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new FileInputStream("xform.xsl")));
StringWriter writer = new StringWriter();
xformer.transform(new StreamSource(new FileInputStream("input.xml")), new StreamResult(writer));
System.out.println(writer.toString());


来源:https://stackoverflow.com/questions/2095673/how-to-remove-the-namespaces-from-the-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!