C# 更新子&x27;XElement(或克隆的XElement)的s属性
我有一个XML,如下所示C# 更新子&x27;XElement(或克隆的XElement)的s属性,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我有一个XML,如下所示 <AFConfig> <Geographies> <Geography id="Place1" description="NicePlace"> <MetaData> <Services> <Service> ... ... </Service> </Services> </MetaData>
<AFConfig>
<Geographies>
<Geography id="Place1" description="NicePlace">
<MetaData>
<Services>
<Service>
...
...
</Service>
</Services>
</MetaData>
<Systems>
<DefaultSystem systemName="SYSONE" server=http"//192.168.0.0" />
</Systems>
</Geography>
<Geographies>
</AFConfig>
...
...
我想做的就是这样
XDocument xd_Document = XDocument.Load(s_FileName);
XElement xe_Element = (from xe in xd_Document.XPathSelectElements(s_Element)
where xe.Attribute(s_IdAttr).Value == s_Value
select xe).SingleOrDefault();
XElement xe_NewElement = CloneElement(xe_Element)
foreach(KeyValuePair<string, string> s in d_AttrValue)
xe_NewElement.Attribute(s.Key).Value = d_AttrValue[s.Key];
xe_Element.Parent.Add(xe_NewElement);
xd_Document.Save(s_destFileName);
XDocument xd_Document=XDocument.Load(s_文件名);
XElement xe_元素=(来自xd_文档中的xe.XPathSelectElements(s_元素)
其中xe.Attribute(s_IdAttr).Value==s_值
选择xe.SingleOrDefault();
XElement xe_新元素=克隆元素(xe_元素)
foreach(d_属性值中的键值对)
xe_NewElement.Attribute(s.Key).Value=d_AttrValue[s.Key];
xe_元素.Parent.Add(xe_新元素);
xd_Document.Save(文件名);
我将以下参数传递给此方法
字符串s_文件名、字符串s_文件名、字符串s_元素、字符串s_IdAttr、字符串s_值、字典d_属性值
通过这段代码,我可以修改id和description属性
问题:如何使用值修改DefaultSystem属性systemName
注意:我有相同的代码用于修改现有元素,而不是创建新元素。我又遇到了同样的问题。最好采用通用解决方案
xe_NewElement.Element("Systems")
.Element("DefaultSystem")
.Attribute("systemName")
.Value = "Enter your value here";
我相信你应该做你需要的
编辑:
var属性=((IEnumerable)xe_NewElement.xpatheevalue(“Systems/DefaultSystem/@systemName”))
.Cast().FirstOrDefault();
attribute.Value=“在此处输入您的值”
应该允许您通过传递XPath和值的列表来完成此操作。Andy:谢谢。但是,我的代码是函数的一部分。我不想硬编码子元素的名称。有没有一种方法,可以说是一种通用的方法来解决这个问题?我已经编辑了我的答案,以包含一个更通用的解决方案。Andy:上面编辑的代码在使用泛型类型“System.Collections.generic.IEnumerable”时出现错误,需要使用“1”类型参数。您可能需要使用System.generic添加参数;安迪:谢谢。我要检查一下。
var attribute = ((IEnumerable)xe_NewElement.XPathEvaluate("Systems/DefaultSystem/@systemName"))
.Cast<XAttribute>().FirstOrDefault();