简体   繁体   English

XElement C#:如何更改 XElement 的值?

[英]XElement C#: How to change the value of XElement?

I have an element that has some value like:我有一个元素具有一些价值,例如:

<Element>
     <I id="I01" class="" /> Some Text
</Element>

How do I keep the "I" element but change the "Some Text" in the Element Tag?如何保留“I”元素但更改元素标签中的“某些文本”?

You can find the right XText child node of Element and set the value of that.您可以找到Element的正确XText子节点并设置其值。 Here's an example, which assumes that it's the first XText node that you're interested in:这是一个示例,它假定它是您感兴趣的第一个XText节点:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XElement element= XElement.Parse(@"
<Element>
    <I id=""I01"" class="""" /> Some Text
</Element>");
        element.DescendantNodes().OfType<XText>().First().Value = "New value";
        Console.WriteLine(element);
    }
}

Output:输出:

<Element>
  <I id="I01" class="" />New value</Element>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM