生成命名空间XML

时间:2012-09-03 19:25:14

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

我尝试向ClaimTypesOffered元素添加更多声明,如下所示:

<fed:ClaimTypesOffered>
  <auth:ClaimType Uri="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" Optional="true" xmlns:auth="http://docs.oasis-open.org/wsfed/authorization/200706">
    <auth:DisplayName>Name</auth:DisplayName>
    <auth:Description>The name of the subject.</auth:Description>
  </auth:ClaimType>
</fed:ClaimTypesOffered>

那里有很多命名空间魔法,我正试图通过它。刚刚获得正确的元素名称一直很困难。我尝试了以下所有方法:

new XElement(XNamespace.Get("auth") + "ClaimType", "somedata");

给出

<ClaimType xmlns="auth">somedata</ClaimType>

new XElement(XName.Get("{http://docs.oasis-open.org/wsfed/authorization/200706}auth"), "somedata");

给出

<auth xmlns="http://docs.oasis-open.org/wsfed/authorization/200706">somedata</auth>

new XElement("auth:ClaimType", "somedata");

给出

System.Xml.XmlException : The ':' character, hexadecimal value 0x3A, cannot be included in a name.

我正在寻求帮助,让我们更进一步,生成声明的完整示例包括属性和内部元素将是非常棒的,即使是正确方向的小推动也会受到赞赏。

1 个答案:

答案 0 :(得分:0)

关键是在父元素上定义命名空间,然后子元素可以使用该命名空间。如果没有 new XAttribute(XNamespace.Xmlns +“auth”,auth.NamespaceName),则会以原始问题中的其他方式定义命名空间。

        XNamespace fed = "http://docs.oasis-open.org/wsfed/federation/200706";
        XNamespace auth = "http://docs.oasis-open.org/wsfed/authorization/200706";

        XElement root = new XElement(auth + "ClaimType",
            new XAttribute(XNamespace.Xmlns + "auth", auth.NamespaceName),
            new XAttribute("Uri", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"),
            new XAttribute("Optional", "true"),
            new XElement(auth+"DisplayName", "EmployeeID"),
            new XElement(auth+"Description", "The employee's designated ID number.")
        );

        Console.WriteLine(root);