从标签中删除命名空间

Remove Namespace from tag

我在 SO 中进行了搜索,但没有找到任何可以解决我的问题的方法。我希望有人能帮助我。

我正在构建一个 XML 文件,我需要删除命名空间 xmlns

这是我的代码

Document xmlDocument = new Document();
Namespace ns1 = Namespace.getNamespace("urn:iso:std:iso:20022:tech:xsd:pain.001.001.03");
Namespace ns2 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
Element root = new Element("Document", ns1);
root.addNamespaceDeclaration(ns2);
xmlDocument.setRootElement(root);
Element CstmrCdtTrfInitn = new Element("CstmrCdtTrfInitn");
root.addContent(CstmrCdtTrfInitn);

PrintDocumentHandler pdh = new PrintDocumentHandler();
pdh.setXmlDocument(xmlDocument);
request.getSession(false).setAttribute("pdh", pdh);

ByteArrayOutputStream sos = new ByteArrayOutputStream();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
Format format = outputter.getFormat();
format.setEncoding(SOPConstants.ENCODING_SCHEMA);
outputter.setFormat(format);
outputter.output(root, sos);
sos.flush();
return sos;

这是创建的XML-文件

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <CstmrCdtTrfInitn xmlns=""/>
</Document>

我必须从标签 CstmrCdtTrfInitn 中删除命名空间 xmlns

非常感谢。

我为你做了一些代码,我不知道你使用的是什么包...如果你只想从 CstmrCdtTrfInitn 标签中删除 xmlns 属性,请尝试使用此代码作为其他生成方法 XML (我刚刚修改了this):

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("Document");
    rootElement.setAttribute("xmlns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03");
    rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

    doc.appendChild(rootElement);

    // staff elements
    Element CstmrCdtTrfInitn = doc.createElement("CstmrCdtTrfInitn");
    rootElement.appendChild(CstmrCdtTrfInitn);


    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    // Output to console for testing
    StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

  } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();
  }

不带前缀 (xmlns="...") 的命名空间声明称为 默认命名空间。请注意,与带前缀的命名空间不同,没有前缀的后代元素继承祖先的默认命名空间隐式。所以在下面的 XML 中, <CstmrCdtTrfInitn> 被认为是在命名空间 urn:iso:std:iso:20022:tech:xsd:pain.001.001.03 :

<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <CstmrCdtTrfInitn/>
</Document>

如果这是想要的结果,与其稍后尝试删除 xmlns="",不如首先尝试使用与 Document 相同的命名空间来创建 CstmrCdtTrfInitn :

Element CstmrCdtTrfInitn = new Element("CstmrCdtTrfInitn", ns1);