【问题标题】:XElement C#: How to change the value of XElement?XElement C#:如何更改 XElement 的值?
【发布时间】:2020-10-12 13:01:39
【问题描述】:

我有一个具有一些价值的元素,例如:

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

如何保留“I”元素但更改元素标签中的“Some Text”?

【问题讨论】:

    标签: c# xelement


    【解决方案1】:

    您可以找到Element 的正确XText 子节点并设置它的值。 这是一个示例,假设它是您感兴趣的第一个 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);
        }
    }
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      相关资源
      最近更新 更多