我想使用 XObjects 以编程方式创建具有命名空间属性和属性值的“dcterms:type”元素。目标xml如下:
<metadata
xmlns="http://example.org/myapp/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example.org/myapp/ http://example.org/myapp/schema.xsd"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:dcterms="http://purl.org/dc/terms/">
...
<dcterms:type xsi:type="dcterms:URI">test</dcterms:type>
...
</metadata>
我努力了:
XNamespace dcterms= XNamespace.Get("http://purl.org/dc/terms/");
XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace dc = XNamespace.Get("http://purl.org/dc/elements/1.1/");
XAttribute xsiAttribute = new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName);
XAttribute dcAttribute = new XAttribute(XNamespace.Xmlns + "dc", dc.NamespaceName);
XAttribute dcmitypeAttribute = new XAttribute(XNamespace.Xmlns + "dcterms", dcterms.NamespaceName);
...
XElement typeElement = new XElement(dc + "type", "test");
XAttribute typeAttribute = new XAttribute(xsi + "type", dcterms + "URI");
typeElement.Add(typeAttribute);
但这会产生:
<dc:type xsi:type="{http://purl.org/dc/terms/}Text">test</dc:type>
...这是错误的,当然,不验证。我还尝试对值进行硬编码:
XAttribute typeAttribute = new XAttribute(xsi + "type", @"dcterms:URI");
这会生成正确的 xml,但会返回“这是一个无效的 xsi:type ' http://purl.org/dc/terms/:Text '。” 通过 XDocument.Validate() 验证时。
想法?