我刚开始使用xml,很难弄清楚这一点。我在网上找到了一个RSS规范的模式,我可以使用xjc
从这个自包含的模式生成java类,没有任何问题。
我想从simpledc.xsd
添加字段,因为在RSS提要中,我在<items>
上看到dc:creator
这样的标签,我想设置它,以便代码生成也可以工作。在我的尝试中,我为dc
模式添加了xsd:include
,并为item
定义添加了一个字段。
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- My addition -->
<xsd:include schemaLocation="simpledc.xsd" />
<xsd:element name="rss" type="rss" />
<xsd:complexType name="rss">
<xsd:sequence>
<xsd:element name="channel" type="channel" maxOccurs="1"
minOccurs="1" />
...
<xsd:complexType name="item">
<xsd:sequence>
<xsd:element name="title" type="xsd:string" maxOccurs="1" minOccurs="0">
<xsd:annotation>
<xsd:documentation>
The title of the item.
</xsd:documentation>
</xsd:annotation>
</xsd:element>
...
<!-- My addition -->
<xsd:element name="creator" type="dc:creator" maxOccurs="1" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
Intellij提供错误:
Cannot resolve symbol 'dc:creator'
和xjc
也提供了类似的错误:
$ xjc -p com.test.generated -d src/main/java/ src/main/resources/schemas/rss.xsd
parsing a schema...
[ERROR] s4s-att-invalid-value: Invalid attribute value for 'type' in element 'element'. Recorded reason: UndeclaredPrefix: Cannot resolve 'dc:creator' as a QName: the prefix 'dc' is not declared.
line 391 of file:/<project>/src/main/resources/schemas/rss.xsd
我如何正确设置,以便我可以在我的xml模式中添加具有dc
名称空间的元素,并使代码正常工作?
我知道该怎么做了。我使用了include
,我应该使用import
,因为我引用了不同的命名空间。然后对于来自不同名称空间的元素,我需要使用ref
来链接到它们:
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<xsd:import schemaLocation="dc.xsd" namespace="http://purl.org/dc/elements/1.1/"/>
...
<xsd:complexType name="item">
<xsd:sequence>
...
<!-- My addition -->
<xsd:element minOccurs="0" ref="dc:creator" />
</xsd:sequence>
</xsd:complexType>
我不确定都柏林核心网站提供的simpledc.xsd
的意图是什么。使用dc.xsd
似乎可以生成模式。
不幸的是,当您尝试根据此模式解组xml时,rss提要作者似乎需要在顶级<rss>
元素中添加xmlns
字段,而他们大多不这样做。