Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# (取消)在XTypedElement元素中正确引用命名空间_C#_Xml_Namespaces_Linq To Xml - Fatal编程技术网

C# (取消)在XTypedElement元素中正确引用命名空间

C# (取消)在XTypedElement元素中正确引用命名空间,c#,xml,namespaces,linq-to-xml,C#,Xml,Namespaces,Linq To Xml,我有一个元素继承自使用LinqToXsd生成的XTypedElement。它具有如下定义的字符串属性: public string lang { get { XAttribute x = this.Attribute(XName.Get("lang", "xml")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String)

我有一个元素继承自使用LinqToXsd生成的XTypedElement。它具有如下定义的字符串属性:

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);
  }
}
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);
  }
}
最初它是用XName.Getlang生成的,但我添加了名称空间XML,因为输出应该如下所示:

<tag xml:lang="nl-NL">...</tag>
相反,我现在得到的是:

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

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

回答我自己的问题:在谷歌搜索了多一点之后,我发现了这个,它成功了:

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", "xml"));
    return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
  }
  set {
    this.SetAttribute(XName.Get("lang", "xml"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
  }
}
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);
  }
}