使用 Linq to XML 删除父元素
我有一个这样的 XML 文件,
<BallList>
<Brand name="xyz">
<BallName>ball A</BallName>
<DateApproved>Jan-12</DateApproved>
<link>www.a.com</link>
</Brand>
<Brand name="abc">
<BallName>Ball B</BallName>
<DateApproved>Jan-02</DateApproved>
<link>www.b.com</link>
</Brand>
</BallList>
这样就有大约 150 个品牌和 8000 个球名。我知道这不是表示 XML 的好方法,但现在由于数据庞大,结构无法修改。
我需要通过将“Brand”节点与其球名进行比较来删除它,
这是我正在尝试的代码:
XElement doc = XElement.Load(Server.MapPath("NetBalls.xml"));
doc.Elements("Brand")
.Where(s => s.Attribute("name").Value == DropDownList1.SelectedItem.Text)
.Elements("BallName")
.Where(l => l.Value == textbox1.Text)
.AncestorsAndSelf()
.Remove();
我正在尝试搜索品牌并进入其元素节点并检查其节点并删除其父节点。
谁能帮我解决这个问题吗?
I have an XML File of this sort
<BallList>
<Brand name="xyz">
<BallName>ball A</BallName>
<DateApproved>Jan-12</DateApproved>
<link>www.a.com</link>
</Brand>
<Brand name="abc">
<BallName>Ball B</BallName>
<DateApproved>Jan-02</DateApproved>
<link>www.b.com</link>
</Brand>
</BallList>
In This way there are around 150 brands and 8000 ball names. I know this is not a good way to represent the XML, but now as the data is huge, structure cannot be modified.
I need to delete "Brand" node by comparing it with its ballname
Here is the code that I am trying out:
XElement doc = XElement.Load(Server.MapPath("NetBalls.xml"));
doc.Elements("Brand")
.Where(s => s.Attribute("name").Value == DropDownList1.SelectedItem.Text)
.Elements("BallName")
.Where(l => l.Value == textbox1.Text)
.AncestorsAndSelf()
.Remove();
I am trying to search for brand and go into its element node and check its node and delete its parent.
Can anyone help me with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无需向下导航到子节点并再次返回,只需将子级条件嵌入到针对您实际想要的元素的
Where
查询中:这样,您的 Linq 查询与您的英语查询更加匹配:“找到所有名称属性为 x、Ballname 元素为 y 的 Brand 元素,并将其删除。”
Instead of navigating down to the child nodes and back up again, just embed the child-level criteria in a
Where
query against the elements you actually want:This way, your Linq query more closely matches your English query: "Find me all of the Brand elements where the name attribute is x, and their Ballname element is y, and remove it."
您想删除品牌元素吗?试试这个:
这将删除所有适用条件的品牌元素。
You want to remove the brand element? Try this:
This will remove all Brand elements where the conditions apply.
您可以将选择条件组合到单个 where 子句中:
You can combine the selection criteria in a single where clause: