c# - Linq2Xml 删除特定属性名称及其值

标签 c# asp.net regex xml

我有这个 XML,我想删除那些: 名称=“项目” Name="shipmentsShipmentIndex"

“名字”是不会变的,

要改变的词是引号之间的词,在这个例子中: itemsshipmentsShipmentIndex

<?xml version="1.0" encoding="UTF-8"?>

 <RootDTO xmlns:json='http://james.newtonking.com/projects/json'>
   <destination>
      <name>XXX</name>
   </destination>
   <orderData>    
      <items json:Array='true'>   
        <shipmentIndex Name="items">0</shipmentIndex>           
      </items>
       <items json:Array='true'>      
        <shipmentIndex Name="items">0</shipmentIndex>           
      </items>

      <shipments json:Array='true'>          
        <shipmentIndex Name="shipmentsShipmentIndex">0</shipmentIndex>                                                          
      </shipments>
   </orderData>
  </RootDTO>

我怎样才能找到所有这些事件并删除它们(或什么都不替换)? 我尝试了很多变体,例如:Name{1}[a-zA-Z]+"\b

最佳答案

您写的是 ASP.NET。您可以使用 Linq2Xml 非常快速地执行此操作(LinqPad 示例):

void Main()
{
    var test = XDocument.Parse("<root><node name=\"name value\">Text</node></root>");
    foreach(var attr in test.Descendants().SelectMany(el=>el.Attributes("name")))
                attr.Remove();

    test.Dump();
}

从这里开始:

<root>
  <node name="name value">Text</node>
</root>

你明白了:

<root>
  <node>Text</node>
</root>

该代码段将从 XML 中除根元素之外的每个元素中删除所有名称属性。如果您想执行其他操作(例如清空属性或包含根元素),请告诉我。

关于c# - Linq2Xml 删除特定属性名称及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35291609/

相关文章:

asp.net - Asp Core 2.0 和 Identity Server v3,受众验证失败

C# 未将对象引用设置为对象的实例

regex - 我如何替换不属于 Perl anchor 标记的文本?

c# - 使用前缀异步时不会触发 Application_Error 处理程序

c# - 字符串到 byte[] 数组,反之亦然

c# - 将 SSIS 包保存到本地机器

asp.net - 我可以从 div onclick 事件调用代码隐藏函数吗?

c# - 您将如何从 MS Project .mpp 文件中提取数据?

javascript - 正则表达式与句子中的分号匹配

javascript - 从数组中查找所有可能的匹配字符串和子字符串