【发布时间】:2012-12-28 20:14:29
【问题描述】:
工作中的一位同事在尝试查询一个非常不寻常的 XML 文件时遇到了问题,在尝试帮助他之后,我和其他人有点创意障碍....看看这个,它可能会引起很多人的兴趣....
结构:
<Root>
<MainFoo>
<Foo>
<A bla="bla" />
<B bla1="blablabla" />
<C bla2="blabla" />
<Bar N="Education" V="Some Text" />
<Bar N="Other Node" V="Some other Text" />
<Bar N="Yet Other Node" V="Some other other Text" />
<Bar N="fourth Bar Node" V="Some other other otherText" />
<Bar N="UserID" V="1" />
</Foo>
<Foo>
<A bla="bla" />
<B bla1="blablabla" />
<C bla2="blabla" />
<Bar N="Education" V="Specific Text" />
<Bar N="Other Node" V="Some other Text" />
<Bar N="Yet Other Node" V="Some other other Text" />
<Bar N="fourth Bar Node" V="Some other other otherText" />
<Bar N="UserID" V="2" />
</Foo>
<Foo>
<A bla="bla" />
<B bla1="blablabla" />
<C bla2="blabla" /> <!--***No Bar node with N="Education" in this Foo Node, not a mistake! this might be part of the problem but this is the XML Structure and can't be changed***-->
<Bar N="Other Node" V="Some other Text" />
<Bar N="Yet Other Node" V="Some other other Text" />
<Bar N="fourth Bar Node" V="Some other other otherText" />
<Bar N="UserID" V="3" />
</Foo>
<Foo>
<A bla="bla" />
<B bla1="blablabla" />
<C bla2="blabla" />
<Bar N="Education" V="Specific Text" />
<Bar N="Other Node" V="Some other Text" />
<Bar N="Yet Other Node" V="Some other other Text" />
<Bar N="fourth Bar Node" V="Some other other otherText" />
<Bar N="UserID" V="4" />
</Foo>
</MainFoo>
<OtherMainFoo></OtherMainFoo>
<MoreMainFoo></MoreMainFoo>
</Root>
好的,现在解决手头的问题: 我们正在尝试使用 LINQ to XML 将每个 每个用户节点的用户 ID 值 转换为每个 Foo 元素的字符串 IF 在这个 Foo 中有一个 Bar 节点 并且这个 Bar 节点的 N 属性 是“教育” 并且只有当这个 具有教育属性的条形节点的 V 值不包含我们在 LINQ 中指定的单词
例如,如果我们希望具有教育的 Foo 节点的所有用户 ID 不包含单词 “Some”,我们将得到 2,4 的结果因为 Foo 编号 1 有一个 Bar 节点,其 N 属性具有教育值,但它在 V 属性中有 Some 字符串,而 Foo 编号 3 在其 N 属性中没有具有 Education 值的 Bar 节点(非常重要,因为我们认为这是我们所做的一切都得到空结果的原因之一)。
这里的任何 LINQ to XML 专家都有一个想法,这对于 XML 来说是一个非常不寻常的场景,但这是我们必须处理的问题,而且我认为这个问题会引起很多人的兴趣。
【问题讨论】:
-
与论坛网站不同,我们不使用“谢谢”、“任何帮助表示赞赏”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?.
-
是否有理由使用 linq 来完成这项任务?这里的业务规则听起来更适合 system.xml
-
首先,不会再发生了,约翰和霍根,为什么不使用 LINQ?它应该执行 System.xml 查询 XML 结构的所有操作,但速度更快,代码行更少,速度更快,或者我错了吗?这不是围绕 LINQ to XML 的全部想法吗?为什么在这里使用 XML 节点查询比使用 LINQ 更好?
-
@Erez - 正如我所说 - 根据用例,一个比另一个更好。如果您不知道如何在 linq 中执行此操作,但知道如何在 System.xml 中执行此操作,这很好地表明 a) System.xml 更好或 b) 您不了解 Linq。我的猜测是 a),但我正在为您提供 linq 答案,请给我几分钟
-
开始和结束标签
<MAinFoo>和</MainFoo>有错别字
标签: c# linq linq-to-xml