【问题标题】:How can I replace something in between xml start tag and xml end tag in c#?如何在 c# 中替换 xml 开始标记和 xml 结束标记之间的内容?
【发布时间】:2020-08-11 08:05:54
【问题描述】:

我有一个xml文件,Body.xml:

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <MyNumbers xmlns="http://google.com/">
      <number1>1</number1>
      <number2>1</number2>
      <number3>1234</number3>
      <number4>1</number5>
    </MyNumbers>
  </soap12:Body>
</soap12:Envelope>

我想以编程方式从数字列表中更改 number3 标记中的数字。 我怎样才能做到这一点?

谢谢!

【问题讨论】:

    标签: c# xml namespaces linq-to-xml


    【解决方案1】:

    MyNumbers 中的默认命名空间发生变化。所以最简单的方法如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                XElement soap = doc.Root;
    
                XElement number3 = doc.Descendants().Where(x => x.Name.LocalName == "number3").FirstOrDefault();
    
                number3.SetValue(5678);
    
            }
        }
    
    }
    

    【讨论】:

    • 非常感谢@jdweng!这对我很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多