【问题标题】:Need to remove XSD files link from xml file using code [duplicate]需要使用代码从 xml 文件中删除 XSD 文件链接 [重复]
【发布时间】:2013-08-15 11:59:01
【问题描述】:

我需要通过代码删除结果标签内的链接。

这是我的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.cfhdocmail.com/TestAPI2/Result.xsd https://www.cfhdocmail.com/TestAPI2/Result.xsd" xmlns="https://www.cfhdocmail.com/TestAPI2/Result.xsd">
  <data>
    <key>MailingGUID</key>
  <value>3699f54b-a05c-45d9-9f91-2d65fea9e2f3</value>
  </data><data>
    <key>OrderRef</key>
  <value>52177</value>
  </data>
</result>

但我想通过代码清空结果标签。我使用了这个代码:

 XmlDocument xml = new XmlDocument();      
 xml.Load(Server.MapPath("~/XMLFile1.xml"));
 // var xdoc = XDocument.Load(xmlFile);
 var configuration = xml.DocumentElement.SelectSingleNode("result");  
 if (configuration != null)
 {               
     // code...
 }

我需要删除结果标签内的链接。

【问题讨论】:

标签: c# asp.net xml


【解决方案1】:

在类文件的顶部添加:

using System.Text.RegularExpressions;

你可以试试这个:

XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/XMLFile1.xml"));
xml.DocumentElement.RemoveAllAttributes();
xml.LoadXml(Regex.Replace(xml.OuterXml, @"xmlns="".*?""", m => ""));

【讨论】:

    【解决方案2】:

    如果您只想删除 &lt;result&gt; 元素上的所有内容(包括 xmlns),请执行以下操作:

    XmlDocument xmldoc = new XmlDocument();
    
    using (XmlTextReader xtr = new XmlTextReader(Server.MapPath("~/XMLFile1.xml")))
    {
        xtr.Namespaces = false;
    
        xmldoc.Load(xtr);
    }
    
    xmldoc.DocumentElement.RemoveAllAttributes();
    

    这将产生这个:

    <?xml version="1.0" encoding="utf-8"?>
    <result>
      <data>
        <key>MailingGUID</key>
      <value>3699f54b-a05c-45d9-9f91-2d65fea9e2f3</value>
      </data><data>
        <key>OrderRef</key>
      <value>52177</value>
      </data>
    </result>
    

    如果您想删除特定的,请使用RemoveAttribute(...)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2012-06-18
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多