【问题标题】:(un)Referencing namespaces correctly in an element of XTypedElement(un) 在 XTypedElement 的元素中正确引用命名空间
【发布时间】:2011-09-19 13:56:34
【问题描述】:

我有一个继承自 XTypedElement 的元素(使用 LinqToXsd 生成)。它有一个这样定义的字符串属性:

public string lang {
  get {
    XAttribute x = this.Attribute(XName.Get("lang", "xml"));
    return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
  }
  set {
    this.SetAttribute(XName.Get("lang", "xml"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
  }
}

最初它是使用 XName.Get("lang") 生成的,但我添加了命名空间“XML”,因为输出应该如下所示:

<tag xml:lang="nl-NL">...</tag>

相反,我现在明白了:

<tag p1:lang="nl-NL" xmlns:p1="xml">...</tag>

以下内容可能完全不相关,但我知道如何使用老派 System.Xml.Serialization.XmlSerializer 类来解决这个问题。您可以在调用 Serialize 方法时指定一些命名空间。 XTypedElement 的 ToString() 没有重载,我可以在其中指定此类命名空间。有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    回答我自己的问题:在谷歌上搜索了一下之后,我发现了这个(并且成功了):

    XName.Get("lang", XNamespace.Xml.NamespaceName)
    

    我确实想知道返回的是什么(只有一个重载,它是一个字符串),所以我在它上面设置了一个断点并读取 XNamespace.Xml.NamespaceName 的值。它是“http://www.w3.org/XML/1998/namespace”。不知何故,Linq-to-xml 似乎知道这与“xml”有什么关系:-)

    现在正确工作的代码如下所示:

    public string lang {
      get {
        XAttribute x = this.Attribute(XName.Get("lang", XNamespace.Xml.NamespaceName));
        return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
      }
      set { 
        this.SetAttribute(XName.Get("lang", XNamespace.Xml.NamespaceName), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 2011-07-27
      • 2019-02-13
      • 2011-06-09
      • 2014-10-15
      • 1970-01-01
      • 2013-12-02
      相关资源
      最近更新 更多