毫升就像thisChange XML节点名称/使用XML节点(C#)
问题描述:
让我们假设我有这样的XML节点方案进行更换:毫升就像thisChange XML节点名称/使用XML节点(C#)
<mat id="4230348">
<home id="2339086"/><away id="2339218"/>
<os/>
</mat>
如何更改节点<os/>
到<os></os>
因为它会导致一个解析问题? 当XML是这样的(包含标签之间的信息,解析是确定的:
<mat id="4230348">
<home id="2339086"/><away id="2339218"/>
<os> <a> <b> </b </a> </os>
</mat>
它读取的东西... ,如果有其他地方的一个节点,其是这样的:
<mat id="4230348">
<home id="2339086"/><away id="2339218"/>
<os/>
</mat>
它无法读取XML文件的其余部分
答
尝试XML的LINQ。LINQ的,你可以投一个元素为字符串,所以如果该项目是空你不会得到一个异常
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program
{
static void Main(string[] args)
{
string input =
"<Root>" +
"<mat id=\"4230348\">" +
"<home id=\"2339086\"/><away id=\"2339218\"/>" +
"<os/>" +
"</mat>" +
"<mat id=\"4230349\">" +
"<home id=\"2339086\"/><away id=\"2339218\"/>" +
"<os/>" +
"</mat>" +
"<mat id=\"4230350\">" +
"<home id=\"2339086\"/><away id=\"2339218\"/>" +
"<os>info</os>. " +
"</mat>" +
"<mat id=\"4230351\">" +
"<home id=\"2339086\"/><away id=\"2339218\"/>" +
"<os/>" +
"</mat>" +
"</Root>";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("mat")
.Select(x => new {
matId = x.Attribute("id").Value,
homeId = x.Element("home").Attribute("id").Value,
awayId = x.Element("away").Attribute("id").Value,
os = (string)x.Element("os")
})
.ToList();
}
}
}
我不清楚“其中”你想这种变化。 XML源文件是一个文本文件,您可以相应地编辑它。您没有指定“解析问题”是什么,但是您可能希望能够将XML源输入到DOM对象并在其中进行操作? – hardmath
您是否需要验证输入文件并删除/修复损坏的节点以继续解析? – Artem
现在的xml是有效的,但我无法用HtmlAgilityPack中的XmlNode方法或HtmlNode解析它。我只想XML节点 变成 ...只是改变字符串 到 如果XML作为atxt文件 –
ABCDD