在查询时使用linq更新xml无法正常工作 [英] Xml updating with linq not working when quering
问题描述
我有问题,我正在尝试使用linq查询更新XML的特定部分,但是它不起作用.所以我是一个xml文件:
I have problem i'm trying to update a specific part of the XML with the linq query but it doesn't work. So i an xml file:
<?xml version="1.0" encoding="utf-8"?>
<DesignConfiguration>
<Design name="CSF_Packages">
<SourceFolder>C:\CSF_Packages</SourceFolder>
<DestinationFolder>C:\Documents and Settings\xxx</DestinationFolder>
<CopyLookups>True</CopyLookups>
<CopyImages>False</CopyImages>
<ImageSourceFolder>None</ImageSourceFolder>
<ImageDesinationFolder>None</ImageDesinationFolder>
</Design>
</DesignConfiguration>
我要选择存在Design name="somethning"
的部分并获取后代,然后更新表示该部分的后代值:
I want to select the part where the part where there is Design name="somethning"
and get the descendants and then update the descendants value that means this part:
<SourceFolder>C:\CSF_Packages</SourceFolder>
<DestinationFolder>C:\Documents and Settings\xxx</DestinationFolder>
<CopyLookups>True</CopyLookups>
<CopyImages>False</CopyImages>
<ImageSourceFolder>None</ImageSourceFolder>
<ImageDesinationFolder>None</ImageDesinationFolder>
我有此代码:
XDocument configXml = XDocument.Load(configXMLFileName);
var updateData = configXml.Descendants("DesignConfiguration").Elements().Where(el => el.Name == "Design" &&
el.Attribute("name").Value.Equals("CSF_Packages")).FirstOrDefault();
configXml.Save(configXMLFileName);
我在updateData
变量中得到了空数据.当我通过QuickWatch尝试Descendat的功能时,它还会返回一个空值.当我检查configXML变量时,它包含的数据就是我的整个xml.我究竟做错了什么?
I'm getting the null data in the updateData
varibale. When I'm trying the Descendat's function through QuickWatch it also returns a null value. When I'm checking the configXML variable it has data that is my whole xml. What am I doing wrong?
推荐答案
由于DesignConfiguration是您的根节点,因此Descendants("DesignConfiguration)返回null.通过使用.Descendants(" Design),您正在查看子项节点,而不是自身.
Because DesignConfiguration was your root node, the Descendants("DesignConfiguration) was returning null. By using the .Descendants("Design"), you were looking at child nodes, not the self.
这篇关于在查询时使用linq更新xml无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!