我有一个存储在数据库中的xml格式字符串,如下所示
第一个
<Query name="test"> <Description />
<Columns>
<Column caption="Activities Name" sorting="None" sortIndex="-1">
<Expr class="ENTATTR" id="Activities.ActivityDescription" />
</Column>
<Column caption="Activities Group" sorting="None" sortIndex="-1">
<Expr class="ENTATTR" id="{Activity Groups}.ActivityGroupDescription" />
</Column>
</Columns>
<JustSortedColumns />
<Conditions linking="All" />
</Query>
在另一个表中,以下xml已存储。
第二个
<Columns>
<Column caption="Activities Note" sorting="None" sortIndex="-1">
<Expr class="ENTATTR" id="Activities.Notes" />
</Column>
<Column caption="Activities Group" sorting="None" sortIndex="-1">
<Expr class="ENTATTR" id="{Activity Groups}.ActivityGroupDescription" />
</Column>
</Columns>
我需要将'<columns>'
和'</columns>'
之间的字符串从第二个替换为第一个。所以更换后:
第一个字符串必须如下:
<Query name="test"> <Description />
<Columns>
<Column caption="Activities Note" sorting="None" sortIndex="-1">
<Expr class="ENTATTR" id="Activities.Notes" />
</Column>
<Column caption="Activities Group" sorting="None" sortIndex="-1">
<Expr class="ENTATTR" id="{Activity Groups}.ActivityGroupDescription" />
</Column>
</Columns>
<JustSortedColumns />
<Conditions linking="All" />
</Query>
答案 0 :(得分:1)
使用LINQ to XML:
测试设置代码:
var s1 = @"<Query name=""test""> <Description />
<Columns>
<Column caption=""Activities Name"" sorting=""None"" sortIndex=""-1"">
<Expr class=""ENTATTR"" id=""Activities.ActivityDescription"" />
</Column>
<Column caption=""Activities Group"" sorting=""None"" sortIndex=""-1"">
<Expr class=""ENTATTR"" id=""{Activity Groups}.ActivityGroupDescription"" />
</Column>
</Columns>
<JustSortedColumns />
<Conditions linking=""All"" />
</Query>";
var s2 = @"<Columns>
<Column caption=""Activities Note"" sorting=""None"" sortIndex=""-1"">
<Expr class=""ENTATTR"" id=""Activities.Notes"" />
</Column>
<Column caption=""Activities Group"" sorting=""None"" sortIndex=""-1"">
<Expr class=""ENTATTR"" id=""{Activity Groups}.ActivityGroupDescription"" />
</Column>
</Columns> ";
实际代码:
var x1 = XElement.Parse(s1);
var x2 = XElement.Parse(s2);
x1.Descendants("Columns").Single()
.ReplaceAll(x2.Descendants("Column"));
var result = x1.ToString();