我试图在其中包含字符串“name”(不区分大小写)的 xml 文件中找到第一个属性,然后更改其值。
这是我的 xml 的示例
//XML 1
<CtApproachTypes
DataclassId="1992A9CE-B048-4676-BFD4-FD81F1A65401"
EntityId="1992A9CE-B048-4676-BFD4-FD81F1A65401"
Name="PAR"
Remark="No Remarks"></CT_ApproachTypes>
//XML 2
<MiMissions
DataclassId="C196A66B-4FA1-461C-9EEF-95A4F2085051"
EntityId="C196A66B-4FA1-461C-9EEF-95A4F2085051"
MissionName="Standard"
Visib="1"></MiMissions>
//XML 3
<StSituations
DataclassId="679FAC3C-C9EF-41FD-9A13-957915605F01"
EntityId="679FAC3C-C9EF-41FD-9A13-957915605F01"
Sname="Standard"
Status="C"
Template="1"></StSituations>
我希望能够修改“Name”、“MissionName”、“Sname”的值,并将它们打印到控制台
编辑 这是我的代码
public void updateXmlFile(string strFileName)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(strFileName);
string newValue = GetUniqueKey();
XmlNodeList list = doc.SelectNodes("@*");
IEnumerable<XmlNode> filteredList= list.Cast<XmlNode>().Where(item=>item.Value.ToLower().Contains("name"));
foreach (XmlNode n in filteredList)
{
Console.WriteLine("NODES ARE : {0}", n);
}
doc.Save(strFileName);
}
catch (XmlException xex) { Console.WriteLine(xex); }
}
这没有打印出任何东西,我仍然需要用字符串 newValue 修改原始值
最佳答案
我会使用 XDocument
object,因为用linq查询很方便。它位于 System.Xml.Linq
命名空间和程序集中。
public void updateXmlFile(string strFileName)
{
XDocument xDoc = XDocument.Load(strFileName);
var nameAttributes = from el in xDoc.Root.Elements()
from attr in el.Attributes()
where attr.Name.ToString().ToLower().Contains("name")
select attr;
foreach (var attribute in nameAttributes)
{
attribute.Value = "newValue";
Console.WriteLine("{0}: {1}", attribute.Name, attribute.Value);
}
xDoc.Save(strFileName);
}
更新
这是输出,给定示例中的 XML,如果将其保存到单个文件中:
Name: newValue
MissionName: newValue
Sname: newValue
关于c# - 使用 LINQ 在 C# 中查找包含特定字符串并修改其值的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3616701/