簡體   English   中英

如何從 xml 元素中刪除屬性?

[英]How to remove an attribute from xml element?

我正在使用 spring java 來解析 xml。

xml 包含以下元素:

 <component xmlns="">
      <nonXMLBody classCode="DOCBODY" moodCode="EVN">
         <text mediaType="application/pdf" representation="B64">zzz</text>
      </nonXMLBody>
 </component>

我需要刪除屬性xmlns=""

我有以下代碼,但屬性xmlns=""仍然存在。

Document dom = null;
try {
                    dom = xmlDocBuilder.parse(inpSource);
                } catch (SAXException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
NodeList nodeComponent = dom.getElementsByTagName("component");
Element element = (Element) nodeComponent.item(0);
element.removeAttribute("xmlns");

根據@Andreas 評論和這個解決方案,我找到了我的解決方案。

正如我在上面的評論中設置的那樣,我在 xml 文檔的開頭還有另一個xmlns屬性,即xmlns="urn:hl7-org:v3"

因此,為了在創建新元素時在新元素中擁有相同的命名空間,我使用以下代碼:

Element root = dom.getDocumentElement();
Element componetEl = dom.createElement("component");
componetEl.setAttribute("xmlns", "urn:hl7-org:v3"); //this is the solution
root.appendChild(componetEl);
Element nonXMLBodyEl = dom.createElement("nonXMLBody");
nonXMLBodyEl.setAttribute("xmlns", "urn:hl7-org:v3"); //this is the solution
...
componetEl.appendChild(nonXMLBodyEl);
Element textEl = dom.createElement("text");
textEl.setAttribute("xmlns", "urn:hl7-org:v3"); //this is the solution
nonXMLBodyEl.appendChild(textEl);

...

因此,現在我的結果 xml 是:

<component>
      <nonXMLBody classCode="DOCBODY" moodCode="EVN">
         <text mediaType="application/pdf" representation="B64">zzz</text>
      </nonXMLBody>
 </component>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM