2016-02-24 31 views
0
<xs:element type="xs:string" name="TheMainElement" maxOccurs="unbounded"> 
    <xs:complexType> 
     <xs:attribute type="xs:string" name="Attribute1OrAttribute2"> 
     </xs:attribute> 
    </xs:complexType> 
</xs:element> 

我已創建的上述XSD以下XML的輸出:XML屬性在Java

<TheMainElement Attribute1OrAttribute2="Attribute1">Text</TheMainElement> 

從Java編碼的角度來看,我理解的元件創建和,如果我試圖對同一該屬性也是如此,它也會有一個末端括號。

Element TheMainElement = document.createElement("TheMainElement"); 

如何添加屬性部分而不出現在最後括號中?

回答

0

看一看org.w3c.dom.Element#setAttribute(String name, String value)

所以你的情況這將是

TheMainElement.setAttribute("Attribute1OrAttribute2", "Attribute1"); 

根據你的需要,你也可以看看org.w3c.dom.Element#setAttributeNode(Attr newAttr)。您必須實現Attr接口或使用已經提供了一些實現的專用庫,例如​​dom4j,這也將幫助您創建操縱XML文檔。

作爲一個側面說明,我會勸阻personnally使用變量的首字母大寫,標準是使用較低的駱駝TheMainElement -> theMainElementgoogle java style guide例如

+0

謝謝!這是我需要的幫助。非常清楚! :) – Dev

+0

另一個類似的說明,如果我想要更多的屬性,我只是將它添加到其他括號? 將在以下... 'TheMainElement.setAttribute( 「Attribute1OrAttribute2」, 「ATTRIBUTE1」, 「額外」, 「AnotherAttribute」);' 產生這種... ' Text' – Dev

+0

如[此方法的文檔]中所述(https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Element.html#setAttribute (java.lang.String,%20java.lang.String)) >如果具有該名稱的屬性已存在於該元素中,則其值將更改爲value參數的值。 – zoom