C# 通过属性从XML中删除重复项
正在尝试删除C# 通过属性从XML中删除重复项,c#,xml,C#,Xml,正在尝试删除任何内容… 如果出现超过1次,则只保留一次 我已经用***包围了我想删除的项目。。 我使用的代码以前工作过,但后来我添加了。Value==“发货” 现在它失败了。 如何保持此代码并仅修复.Value==“装运”以使其正常工作 class Program { static void Main(string[] args) { string renderedOutput = "<
任何内容…
如果出现超过1次,则只保留一次
我已经用***包围了我想删除的项目。。
我使用的代码以前工作过,但后来我添加了。Value==“发货”
现在它失败了。
如何保持此代码并仅修复.Value==“装运”
以使其正常工作
class Program
{
static void Main(string[] args)
{
string renderedOutput =
"<?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\" >111</shipmentIndex>" +
"<barcode>12345</barcode>" +
"</items>" +
"<items json:Array='true'>" +
"<shipmentIndex Name=\"items\">222</shipmentIndex>" +
"<barcode>12345</barcode>" +
"</items>" +
"<items json:Array='true'>" +
"<shipmentIndex Name=\"items\">222</shipmentIndex>" +
"<barcode>12345</barcode>" +
"</items>" +
"<misCode>9876543210</misCode>" +
"<shipments>" +
"<sourceShipmentId></sourceShipmentId>" +
"<shipmentIndex shipments=\"shipments\">111</shipmentIndex>" +
"</shipments>" +
"<shipments>" +
"<sourceShipmentId></sourceShipmentId>" +
"<shipmentIndex Name=\"shipments\">222</shipmentIndex>" +
****
"<shipmentIndex Name=\"shipments\">222</shipmentIndex>" +
****
"</shipments>" +
"</orderData>" +
"</RootDTO>";
var xml = XElement.Parse(renderedOutput);
xml.Element("orderData").Descendants("shipments")
.SelectMany(s => s.Elements("shipmentIndex")
.GroupBy(g => g.Attribute("Name").Value == "shipments")
.SelectMany(m => m.Skip(1))).Remove();
}
}
类程序
{
静态void Main(字符串[]参数)
{
字符串渲染输出=
"" +
"" +
"" +
“xxx”+
"" +
"" +
"" +
"111" +
"12345" +
"" +
"" +
"222" +
"12345" +
"" +
"" +
"222" +
"12345" +
"" +
"9876543210" +
"" +
"" +
"111" +
"" +
"" +
"" +
"222" +
****
"222" +
****
"" +
"" +
"";
var xml=XElement.Parse(renderOutput);
xml.Element(“orderData”).子体(“装运”)
.SelectMany(s=>s.Elements(“shipmentIndex”)
.GroupBy(g=>g.Attribute(“名称”).Value==“装运”)
.SelectMany(m=>m.Skip(1)).Remove();
}
}
我不确定我是否100%理解了这个问题,但下面是:
我认为您希望过滤结果,以便只包含name属性等于'shippings'的元素,尽管并非所有shipmentIndex元素都具有'name'属性,因此您可能会得到一个null引用异常。您需要添加检查以确保“Name”属性存在
xml.Element("orderData").Descendants("shipments")
.SelectMany(s => s.Elements("shipmentIndex")
.GroupBy(g => g.Attribute("Name") != null && g.Attribute("Name").Value == "shipments")
.SelectMany(m => m.Skip(1))).Remove();
如果要从RenderOutput字符串中删除重复项:
Match match = Regex.Match(renderedOutput, "<shipmentIndex Name=\"shipments\">([^<]*)</shipmentIndex>");
int index = renderedOutput.IndexOf(match.ToString());
renderedOutput = renderedOutput.Remove(index, match.ToString().Length);
Match Match=Regex.Match(renderoutput),([^i只想从子体(“装运”)中删除此项。