c# - Linq 2 XML - 如何读取具有相同名称的元素
xml的结构是:
<Rules>
<rule ID="1" Parameter="IsD">
<body>
<ID>2</ID>
<Ratio>=</Ratio>
<Value>no</Value>
<Operation>AND</Operation>
<ID>3</IF_ID>
<Ratio>=</Ratio>
<Value>yes</Value>
</body>
<value>no problems</value>
</rule>
</Rules>
如何读取元素并创建具有以下结构的规则:
If (<ID><Ratio><Value><Operation><ID><Ratio><Value>)
ID是问题ID。就我而言:
If (2 == no && 3 == yes)
请帮助我。
the stucture of xml is:
<Rules>
<rule ID="1" Parameter="IsD">
<body>
<ID>2</ID>
<Ratio>=</Ratio>
<Value>no</Value>
<Operation>AND</Operation>
<ID>3</IF_ID>
<Ratio>=</Ratio>
<Value>yes</Value>
</body>
<value>no problems</value>
</rule>
</Rules>
How can I read elements and create a rule with the following structure:
If (<ID><Ratio><Value><Operation><ID><Ratio><Value>)
ID is a question ID. In my case:
If (2 == no && 3 == yes)
Please, help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
XElement
类的Elements
方法。例如(假设您循环遍历所有rule
),您可以编写Notet,通过使用
ElementAt()
Elements 枚举的元素> 可能不是很有效,另一种方法是使用单独的foreach
循环迭代不同的子元素并将它们存储在List
中(或者更好,使用ToList
扩展方法)。要点是,
Elements
枚举按文档顺序返回子元素,即按照它们在输入文档中出现的顺序(这就是您在这里需要的)。更好的解决方案是(IMO)在输入文档中添加更多结构以反映逻辑,例如:
You could use the
Elements
method of theXElement
class. For instance (supposing that you loop over allrule
s) you could writeNotet that accessing the elements of the
Elements
enumeration by use ofElementAt()
might not be very efficient, another approach would be to iterate over the different subelements with separateforeach
loops and store them in aList
(or better, use theToList
Extension method).The point is, that the
Elements
enumeration returns the subelements in document order i.e. in the same order as they appear in the input document (which is, what you need here).A better solution would be (IMO) to put more structure in your input document in order to reflect the logic, like: