我正試圖通過將 XML 檔案加載到 Document 物件中并在那里對其進行操作來以編程方式編輯該檔案。 然而,如果我將 XML 加載到 InputStream 中或將其寫回檔案中,所有的豆類標簽都被添加了 xmlns="" 屬性,程式中的這一部分可以正常作業。
所以如果之前我有:
< bean id="discoverySpi"/span> class="org. apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">。
< property name="ipFinder" ref="ipFinder" />
</bean>
我又出來了:
< bean xmlns=""/span> class="org. apache.ignite.spi.discovery.tcp.TcpDiscoverySpi" id="discoverySpi">
< property name="ipFinder" ref="ipFinder"/>
</bean>/span>
這種情況發生在所有bean標簽上,無論它們是否被編輯過。 我驗證了簡單地讀取 XML 檔案并使用以下代碼將其寫回,而不對 Document 物件做任何更改,仍然會導致錯誤。
我認為這是在我創建 DOMSource 物件時發生的,但不知道如何阻止這種情況的發生。
目前,當我試圖使用XML檔案時,這些添加的屬性會導致錯誤。
String XML_PATH = " 。 /some/path/in/project/someXML.xml"。
DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance() 。
DocumentBuilder docBuilder = docBF.newDocumentBuilder()。
Document doc = docBuilder.parse(XML_PATH)。
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer()。
DOMSource domSource = new DOMSource(doc)。
StreamResult streamResult = new StreamResult(new File(" 。 /some/output/path/modifiedXml.xml"))。)
transformer.transform(domSource, streamResult)。
uj5u.com熱心網友回復:
首先,添加
docBF.setNamespaceAware(true)。
其次,確保每當你以編程方式向DOM添加一個元素時,你都會使用命名空間感知版本的方法,例如 考慮使用 XOM 或 JDOM2 等庫,以優先于 DOM。當有更好的替代方案時,DOM的流行從未停止過讓我感到震驚。
標籤:createElementNS()/code>。
