【发布时间】:2009-07-08 23:30:25
【问题描述】:
我有一个简单的 POCO 类来保存从 XML 文件中提取的数据,定义如下:
public class Demographics
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Gender { get; set; }
}
我有一个相当简单的 XML 文件(在这种情况下是元素)来提取数据,定义如下:
<patient determinerCode="INSTANCE">
<name use="L">
<given>John</given>
<given qualifier="IN">Q.</given>
<family>Public</family>
</name>
<administrativeGenderCode code="F" displayName="Female"/>
</patient>
我面临的挑战是将中间名首字母和/或名字放入班级中的正确属性中。如您所见,name 节点内有两个 given 节点,中间的首字母由“IN”属性。是否有我在这里遗漏的简单 LINQ 语法,还是我需要查询所有给定节点并枚举它们以正确放置每个节点?
我目前的代码如下所示:
private string GetInterfaceXmlData(XElement source)
{
//Source in this context represents the "patient" element as you see in the example.
//The NMSPC constant represents the namespace for this XML document which is not specifically displayed
//in the XML example.
Demographics currentDemo = new Demographics()
{
//I realize that this particular reference to FirstName is not optimal, as it may not actually
//be the first "given" node under the name node, it's simply a place holder for now.
FirstName = source.Element(NMSPC + "name").Element(NMSPC + "given").Value,
LastName = source.Element(NMSPC + "name").Element(NMSPC + "family").Value,
Gender=source.Element(NMSPC+"administrativeGenderCode").Attribute("code").Value,
};
XElement result = new XElement("XML");
result.Add(new XElement("Demographics"));
return result.ToString();
}
【问题讨论】:
标签: c# linq linq-to-xml