使用XAttribute添加和验证命名空间属性值

时间:2013-03-02 03:37:54

标签: c# xml linq linq-to-xml

我想以编程方式使用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()验证时。

想法?

0 个答案:

没有答案
相关问题