[英]LINQ to XML Syntax
I've got a simple POCO class to hold data extracted from an XML file defined as follows: 我有一个简单的POCO类,用于保存从XML文件中提取的数据,该XML文件定义如下:
public class Demographics
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Gender { get; set; }
}
I've got a fairly straight-forward XML file (or rather element in this case) to extract data from, defined as follows: 我有一个相当简单的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>
The challenge I'm having is getting the middle initial and/or first name into the correct properties in my class. 我面临的挑战是将中间的名字首字母和/或名字放入类中的正确属性中。 As you can see, there are two given nodes inside the name node and the middle initial is designated by an "IN" attribute.
如您所见, 名称节点内有两个给定的节点,中间的首字母由“ IN”属性指定。 Is there a simply LINQ syntax that I'm missing here, or do I need to query for all the given nodes and enumerate through them to properly place each node?
我是否在这里缺少简单的LINQ语法,还是需要查询所有给定的节点并枚举它们以正确放置每个节点?
My code as it currently stands, looks like this: 我目前的代码如下所示:
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();
}
How about: 怎么样:
// For the first name
source.Element(NMSPC + "name")
.Elements(NMSPC + "given")
.Where(element => element.Attribute("IN") == null)
.First()
// For the initial
source.Element(NMSPC + "name")
.Elements(NMSPC + "given")
.Where(element => element.Attribute("IN") != null)
.First()
EDIT: Query syntax is a bit awkward here. 编辑:查询语法在这里有点尴尬。 For the first version, it would be:
对于第一个版本,它将是:
(from element in .Element(NMSPC + "name").Elements(NMSPC + "given")
where element.Attribute("IN") == null
select element).First()
I'd personally stick to dot notation for this. 我个人会为此坚持点符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.