我有如下的XML显示RoadPart和Vehicles元素:
<RoadPart>
<Vehicles>
<ConfigurationSummaryListPosition>
<ConfigurationSummary>Test name</ConfigurationSummary>
</ConfigurationSummaryListPosition>
</Vehicles>
<Vehicles>
<ConfigurationSummaryListPosition>
<ConfigurationSummary>Test name</ConfigurationSummary>
</ConfigurationSummaryListPosition>
</Vehicles>
<Vehicles>
<ConfigurationSummaryListPosition>
<ConfigurationSummary>Test name</ConfigurationSummary>
</ConfigurationSummaryListPosition>
</Vehicles>
</RoadPart>
我有一个变量
var test = @"<DataType>
<ConfigurationSummaryListPositionType>
<ConfigurationSummaryType> name </ConfigurationSummaryType>
</ConfigurationSummaryListPositionType>
</DataType>
<DataType>
<ConfigurationSummaryListPositionType>
<ConfigurationSummaryType> Test</ConfigurationSummaryType>
</ConfigurationSummaryListPositionType>
</DataType>";
想要更换具有可变输出的车辆元素应如下:
<RoadPart>
<DataType>
<ConfigurationSummaryListPositionType>
<ConfigurationSummaryType> name </ConfigurationSummaryType>
</ConfigurationSummaryListPositionType>
</DataType>
<DataType>
<ConfigurationSummaryListPositionType>
<ConfigurationSummaryType> Test</ConfigurationSummaryType>
</ConfigurationSummaryListPositionType>
</DataType>
</RoadPart>
帮我解决这个问题
答案 0 :(得分:0)
为什么不用linq读取xml,重复每个节点并更改该节点值。
var nodes = (from node in document.Descendant("RoadPart") select node);
其中document是加载的xml文件
var document = XDocument.Load("your xml file path");
然后像你一样在文档中引用foreach节点
foreach (var node in nodes)
{
// do something
}
答案 1 :(得分:0)
这会将结果返回为System.Xml.Linq.XElement
:
test = string.Concat("<root>", test, "</root>"); // set dummy root
XDocument xdoc = XDocument.Parse(test);
XElement replaced = new XElement("RoadPart", xdoc.Descendants("DataType").Select(e => e));
如果要将结果保存为文件,
using (FileStream fs = new FileStream("{filePath}", FileMode.Create))
{
replaced.Save(fs);
fs.Close();
}