XML Java 中的属性

XML Attribute In Java

<xs:element type="xs:string" name="TheMainElement" maxOccurs="unbounded">
    <xs:complexType>
        <xs:attribute type="xs:string" name="Attribute1OrAttribute2">
        </xs:attribute>
    </xs:complexType>
</xs:element>

我已经为以下 XML 的输出创建了上面的 XSD:

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

从 java 编码的角度来看,我理解元素的创建,如果我也尝试对属性进行相同的操作,它也会有一个结束括号。

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

如何添加属性部分而不使其出现在结尾括号中?

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

所以你的情况是

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

根据您的需要,您也可以看看org.w3c.dom.Element#setAttributeNode(Attr newAttr)。您将必须实现 Attr 接口或使用已经提供一些实现的专用库,例如​​ dom4j,这也将帮助您创建一个可操作的 XML 文档。

附带说明一下,我个人不鼓励使用首字母大写的变量,标准是使用小驼峰式 TheMainElement -> theMainElement 参见 google java style guide 例如