【问题标题】:How to send value of XML tags如何发送 XML 标签的值
【发布时间】:2018-07-15 15:02:22
【问题描述】:

我有一个外部 CML 文件,我已将其保存在 Asp.Net mvc 项目的 Xml 文件夹中我正在尝试使用字符串编写器替换我写在方括号 [] 中的 xml 文件的字符串>

string lStrXMLRequest = System.Web.HttpContext.Current.Server.MapPath("/Xml/SoapAvailabilitySearch.xml");

StreamReader str = new StreamReader(lStrXMLRequest);
string XMLText = str.ReadToEnd();
str.Close();
XMLText.Replace("[orgname]",org);

但是我看到 orgname 没有被 org 变量中发送的值替换。谁能告诉我如何将值从 c# 发送到 XML 文件。

这是我的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <AvailabilitySearch xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
      <xiRequest>
        <Authority>
          <Org>[orgname]</Org>
          </Authority>
          </xiRequest>
    </AvailabilitySearch>
  </soap:Body>
</soap:Envelope>

任何帮助将不胜感激。

【问题讨论】:

  • 这会将文件内容替换为新字符串string xml = File.ReadAllText(lStrXMLRequest); File.WriteAllText(lStrXMLRequest, xml.Replace("[orgname]", org));

标签: c# xml asp.net-mvc asp.net-mvc-4


【解决方案1】:

您已经编写了一个 XML 文件,但其中一个字段不正确,因此您决定将其作为文本加载到内存中,然后进行字符串替换,而不是在写入之前更正该字段?

如果该文件是 100MB 或 10GB 怎么办?您可能很难将其加载到内存中只是为了进行字符串替换!

为什么不首先修复文件?

【讨论】:

  • 我现在已经更正了 xml。如果替换不是一个好主意,那么将值从 c# 发送到 [orgname] 中的 xml 文件的理想方法是什么
  • 最初是如何创建 XML 文件的?
  • 我在问题中提到我的项目的 xml 文件夹中有一个 .xml 文件。我已经有了 xml 文件,只是标签内的值是动态的,所以我如何将值从 c# 发送到标签
  • 所以,这不是一个关于 XML 的问题,而是一个关于如何替换文本文件中的标签的问题?
【解决方案2】:

您最初的尝试没有正确使用string.Replace。字符串是不可变的,因此此方法返回一个新字符串,其中旧文本替换为新文本。您的代码没有将它分配给任何东西,所以当方法完成时它会被丢弃。

这将满足您的需求,但内存效率不高,因为您必须将整个文件读入内存才能执行替换。

另一种方法是使用XmlReader 和 XmlWriter 使用读取器从文件中一次读取一个节点并将它们传递给写入器,有条件地将更新的元素值写入节点序列中找到的位置。

【讨论】:

    【解决方案3】:

    xml 有一个必须正确处理的命名空间。他是使用 Xml Linq 改变价值的一种方式:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                string lStrXMLRequest = File.ReadAllText(FILENAME);
    
                XDocument doc = XDocument.Parse(lStrXMLRequest);
    
    
                XElement ord = doc.Descendants().Where(x => x.Name.LocalName == "Org").FirstOrDefault();
    
                ord.SetValue("abc");
    
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2021-05-12
      相关资源
      最近更新 更多