将新 XElement 添加到现有 XElement(如果尚不存在)
在尝试添加某个元素之前,如何检查该元素是否存在于给定元素中?
背景:我有一个XDocument
X
,其中包含子元素Flowers
,随后包含一系列元素每个都被命名为Flower
。每个 Flower
已经有 2 个子元素,我想添加一个名为 Price
的第三个元素。但是,我想检查并确保 Flower
元素中尚不存在 Price
元素。我该怎么做?我还需要检查吗?
How do I check to see if an element exists within a given element before trying to add it?
Background: I have an XDocument
X
that contains as a child element Flowers
which subsequently contains a series of elements that are each named Flower
. Each Flower
already has 2 child elements and I would like to add a 3rd element called Price
. However, I want to check and make sure there's not already an element for Price
within the Flower
element. How do I do that? Do I even need to check?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
XElement
有一个HasElements
属性,如果只是想知道是否存在任何元素,该属性就可以工作。对于您的情况,我将使用...
..来查看价格元素是否存在。如果没有,您可以添加它。
注意:如果您没有为 XML 文件设置任何命名空间,则可以使用
Namespace.None
而不是ns
。XElement
has aHasElements
property, which would work if just wanted to know whether any elements existed or not.For your case, I would use...
..to see if a the price element exists. If not, you can then add it.
Note: if you don't have any namespace set for your XML file, you can use
Namespace.None
instead ofns
.