如何用冒号反序列化 XML 元素?

问题描述 投票:0回答:1

我需要一些关于 C# (.NET) 中 System.XML 的帮助。

我在 .xml 文件中的某处有此文本:

<Location>
    <Longitude>9.118782</Longitude>
    <Latitude>50.178153</Latitude>
    <gml:pos>104049 489104</gml:pos>
</Location>

由于第三个字段名称中有一个冒号,我不能将其用作变量。 因此,我的反序列化类(通过 XmlSerializer.Deserialize)如下所示:

public class Location
{
    public decimal Longitude { get; set; }      // this works!
    public decimal Latitude { get; set; }       // this works!

    [XmlAttribute("gml:pos")]
    public string GmlPos { get; set; }
}

抛出异常。我对 XML 不是很熟悉,但由于异常,我发现冒号代表 XML 命名空间,所以我也尝试了这些不同的选项(当然是同时尝试):

[XmlAttribute("pos", Namespace = "gml")]
public string GmlPos { get; set; }

[XmlAttribute("pos", Namespace = "gml/")]
public string GmlPos { get; set; }

[XmlAttribute(Namespace = "gml")]
public string pos { get; set; }

[XmlAttribute(Namespace = "gml/")]
public string pos { get; set; }

没有异常,但该字段仍然为空。我还用 XmlElement 而不是 XmlAttribute 尝试了每个选项。

不幸的是,这不容易用谷歌搜索,因为短语“命名空间”总是导致 System.XML ...

请不要建议更改 .xml 文件;)

感谢您的每一次帮助, 蒂姆

c# xml deserialization xml-namespaces
1个回答
2
投票

gml
不是这里的命名空间——它是一个命名空间别名。一旦你弄清楚了 actual 命名空间是什么(寻找
xmlns:gml="..."
),你就可以按照你的第一个例子在 XmlAttribute 中指定它。我怀疑命名空间是http://www.opengis.net/gml/3.2,在这种情况下你会:

[XmlAttribute("pos", Namespace="http://www.opengis.net/gml/3.2")]
public string GmlPos { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.