繁体   English   中英

使用C#更改Xml文件的内部文本

[英]Change the inner text of Xml file using c#

我有以下具有名称空间的XML文件,如下所示:

我必须更改XML文件的内部文本,但需要建议如何做。

我的XML文件是:

    <?xml version="1.0"?>
    <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
      <buttons>
        <workshop1>Google</workshop1>
<workshop1>Yahoo</workshop1>
        <url1>www.google.co.uk</url1>
      </buttons>
    </Report>

我必须将第二个节点workshop1的内部文本从“ Yahoo”更改为“ new”。

使用XElement执行此操作。

您可能遇到的“问题”是由于该xml具有的命名空间引起的:

    XElement xml = getXml(); // get your xml from a service\file\ftp etc..
    XNamespace ns = "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition";
    xml.Descendants(ns + "workshop1").First().Value = "new";

您的输出:

<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
  <buttons>
    <workshop1>new</workshop1>
    <url1>www.google.co.uk</url1>
  </buttons>
</Report>

对于多个节点,请使用以下命令:

    XNamespace ns = "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition";
    var nodes = xml.Descendants(ns + "workshop1").ToList();
    nodes[0].Value = "new";
    nodes[1].Value = "new2"; 
    // etc.... 

暂无
暂无

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

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