使用 LINQ Select 插入 XElement?
我有一个 xml 源代码片段,我想在其中插入多个元素,这些元素是根据原始 xml 中找到的某些值创建的。
目前,我有一个子程序可以为我执行此操作:
<Extension()>
Public Sub AddElements(ByVal xml As XElement, ByVal elementList As IEnumerable(Of XElement))
For Each e In elementList
xml.Add(e)
Next
End Sub
这在例程中被调用,如下所示:
Dim myElement = New XElement("NewElements")
myElement.AddElements(
xml.Descendants("TheElements").
Where(Function(e) e.Attribute("FilterElement") IsNot Nothing).
Select(Function(e) New XElement("NewElement", New XAttribute("Text", e.Attribute("FilterElement").Value))))
是否可以使用 Linq 语法重新编写此代码,这样我就不需要调用 Sub AddElements,但可以内联完成所有操作
Many Thx
Simon
I have a source piece of xml into which I want to insert multiple elements which are created dependant upon certain values found in the original xml
At present I have a sub which does this for me:
<Extension()>
Public Sub AddElements(ByVal xml As XElement, ByVal elementList As IEnumerable(Of XElement))
For Each e In elementList
xml.Add(e)
Next
End Sub
And this is getting invoked in a routine as follows:
Dim myElement = New XElement("NewElements")
myElement.AddElements(
xml.Descendants("TheElements").
Where(Function(e) e.Attribute("FilterElement") IsNot Nothing).
Select(Function(e) New XElement("NewElement", New XAttribute("Text", e.Attribute("FilterElement").Value))))
Is it possible to re-write this using Linq syntax so I don't need to call out to the Sub AddElements but could do it all in-line
Many Thx
Simon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然:
XElement
和XAttribute
具有构造函数(除了元素或属性名称之外)接受任意数量的对象(它们本身可以是查询或其他 IEnumerables) )。传递给构造函数的任何内容都会作为内容添加。您可能还想研究 XML 文字,这使得它更具可读性,但本质上做的是同样的事情。
使用 XML 文字,它看起来像这样:
< %=
%>
在 XML 中嵌入 VB 表达式的值xml...
选择名为 elemname这几乎是 XQuery ;-)。
Sure:
XElement
andXAttribute
have constructors which (in addition to the element or attribute name) accept an arbitrary number of objects (which themselves can be queries or otherIEnumerables
). Anything you pass to the constructor is added as content.You may also want to look into XML-literals, which make this much more readable but essentially do the same thing.
With XML Literals, it looks like this:
<%=
%>
embeds a VB expression's value in XMLxml...<elemname>
selects descendants of xml called elemnameIt's almost XQuery ;-).