如何为 XML 元素之间的数据编写 linq-to-xml?
我正在尝试解析一些类似于以下内容的 XML:
<document>
<headings>
Important heading stuff.
</headings>
<startGroup group="1" />
<startItem value="1" />Item one stuff<endItem />
<blockofdata>
<startItem value="2" />Item two stuff<endItem />
<startItem value="3" />Item three stuff<endItem />
</blockofdata>
<startItem value="4" />Item four stuff<endItem />
<endGroup />
<startGroup group="2" />
<startItem value="1" />Item one stuff<endItem />
<startItem value="2" />Item two stuff<endItem />
<startItem value="3" />Item three stuff<endItem />
<endGroup />
</document>
我无法找出 linq-to-xml 语句来获取我想要的内容。我需要扁平化结构。因此,假设上面的 XML,我想获取此 POCO 的列表:
class Items
{
public int GroupNumber {get;set;} // group property of startGroup
public int ItemNumber {get;set;} // value property of startItem
public string ItemText {get;set;} // data between i
}
How do you write a linq-to-xml statements that will pull the data between the attribute into the上面的项目,同时从 startGroup/endGroup 和之间获取数据startItem/endItem 之间的数据?我已经为此花费了几个小时,并且即将改用 XML 流读取器并以老式方式解析它。
I am trying to parse some XML that looks similar to this:
<document>
<headings>
Important heading stuff.
</headings>
<startGroup group="1" />
<startItem value="1" />Item one stuff<endItem />
<blockofdata>
<startItem value="2" />Item two stuff<endItem />
<startItem value="3" />Item three stuff<endItem />
</blockofdata>
<startItem value="4" />Item four stuff<endItem />
<endGroup />
<startGroup group="2" />
<startItem value="1" />Item one stuff<endItem />
<startItem value="2" />Item two stuff<endItem />
<startItem value="3" />Item three stuff<endItem />
<endGroup />
</document>
I cannot figure out a linq-to-xml statement to get what I want. I need to flatten the structure. So assuming the above XML, I would like to get a list of this POCO:
class Items
{
public int GroupNumber {get;set;} // group property of startGroup
public int ItemNumber {get;set;} // value property of startItem
public string ItemText {get;set;} // data between i
}
How do you write a linq-to-xml statement that would pull the data between the attributes into the above item while grabing the data from between startGroup/endGroup and the data between startItem/endItem? I have burned up several hours on this and am about to just switch to using a XML stream reader and parsing it the old fashioned way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的关键是使用
ElementsAfterSelf()
和NodesAfterSelf()
方法来抓取兄弟节点以及TakeWhile()
谓词来停止在适当的时候进行枚举。首先是辅助方法:
以及神奇的查询。
现在我希望您没有自己设计这个 XML...这是一种真正可以将某人推向边缘的东西。 ;)
The key here is to use the
ElementsAfterSelf()
andNodesAfterSelf()
methods to grab the sibling nodes along with theTakeWhile()
predicate to stop enumerating at the appropriate times.First the helper methods:
And the magic query.
Now I hope you did not design this XML yourself... this is the kind of stuff that can really push someone over the edge. ;)