LINQtoXML 嵌套集合和值?
我有一些 XML:
<Request>
<EmailAddress>string</EmailAddress>
<Item>
<name>FirstName</name>
<value>John</value>
</Item>
<Item>
<name>LastName</name>
<value>Doe</value>
</Item>
</Request>
我的对象:
public class TheObject{
public string EmailAddress { get; set; }
public string SkuNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想使用 LINQtoXML 从上面的 XML 中提取 FirstName 和 LastName 值来构建对象。我该怎么做?
更新:这是我开始的代码:
var object =
xml.Descendants("Request").Select(
x =>
new TheObject()
{
EmailAddress = x.Element("EmailAddress").Value.ToString(),
SkuNumber = x.Element("SKU").Value.ToString(),
FirstName = ...,
LastName = ....
})
I have some XML:
<Request>
<EmailAddress>string</EmailAddress>
<Item>
<name>FirstName</name>
<value>John</value>
</Item>
<Item>
<name>LastName</name>
<value>Doe</value>
</Item>
</Request>
My object:
public class TheObject{
public string EmailAddress { get; set; }
public string SkuNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
I want to use LINQtoXML to pull out the FirstName and LastName values from the above XML to build the object. How would I do this?
Update: Here is my code I started:
var object =
xml.Descendants("Request").Select(
x =>
new TheObject()
{
EmailAddress = x.Element("EmailAddress").Value.ToString(),
SkuNumber = x.Element("SKU").Value.ToString(),
FirstName = ...,
LastName = ....
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如其他人所指出的,如果您可以控制 XML 结构,则可以更好地针对此类查询对其进行优化。但是,如果您坚持使用它并且想要在单个 LINQ to XML 中处理它,您可以执行类似以下操作(为简洁起见,我省略了空引用/异常处理,具体取决于您的架构,您可能希望将其扩展以涵盖这些领域)
希望这有助于解决问题。
As others have pointed out if you had control of the XML structure you could optimise it better for this type of querying. However if you are stuck with it and you want to handle it in a single LINQ to XML you could do something like the following (I've omitted null reference/exception handling for brevity depending on your schema you might want to extend this to cover these areas)
Hope this helps with the problem.
将 LINQToXML 与 xpath 的明智使用相结合,也许在您的投影中。我不记得确切的语法,但你的 xpath 会是这样的:
你可以用你的“FirstName”或“LastName”替换 {PropertyName}。
Combine your LINQToXML with judicious use of xpath, perhaps in your projection. I don't remember the exact syntax, but your xpath would be something like:
You would substitute your "FirstName" or "LastName" for {PropertyName}.
如果您不需要 XPath,您可以将 xml 加载到 XElement 中,然后获取项目,例如
或类似的内容。
编辑:
如果您的 xml 看起来更像这样,那么您可以使用
XmlSerializer
在对象和 xml 之间来回切换。If you don't want XPath, you can load the xml into an XElement and then get the items, eg
Or something like that.
EDIT:
If your xml looked more like this, then you could use
XmlSerializer
to go back and forth between your object and xml.