我确信这是基本的,可能之前曾被问到过,但我只是开始使用Linq到XML。Linq to XML - 找到一个元素
我有一个简单的XML,我需要读取和写入。
<Documents>
...
<Document>
<GUID>09a1f55f-c248-44cd-9460-c0aab7c017c9-0</GUID>
<ArchiveTime>2012-05-15T14:27:58.5270023+02:00</ArchiveTime>
<ArchiveTimeUtc>2012-05-15T12:27:58.5270023Z</ArchiveTimeUtc>
<IndexDatas>
<IndexData>
<Name>Name1</Name>
<Value>Some value</Value>
<DataType>1</DataType>
<CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime>
<CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc>
</IndexData>
<IndexData>
<Name>Name2</Name>
<Value>Some value</Value>
<DataType>3</DataType>
<CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime>
<CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc>
</IndexData>
...
</IndexDatas>
</Document>
...
</Documents>
我有一个“文档”节点,其中包含一堆“文档”节点。
我有文档的GUID和“IndexData”名称。 我需要通过GUID查找文档,并检查它是否带有某个名称的“IndexData”。 如果它没有它,我需要添加它。
任何帮助将是apreciated,因为我有阅读和搜索槽元素的问题。
目前,我尝试使用(在C#):
IEnumerable<XElement> xmlDocuments = from c in XElement
.Load(filePath)
.Elements("Documents")
select c;
// fetch document
XElement documentElementToEdit = (from c in xmlDocuments where
(string)c.Element("GUID").Value == GUID select c).Single();
编辑
xmlDocuments.Element("Documents").Elements("Document")
这将返回任何结果,即使寿xmlDocuments.Element( “文档”)一样。它看起来像我不能从文档节点获取文档节点。
我认为这应该是'doc.Descendants( “文档”)' – 2012-07-06 06:36:52
谢谢,固定。 – 2012-07-06 06:41:26