我确定这是基础问题,可能以前已经被问过了,但我刚开始使用 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”。 如果没有,我需要添加它。
任何帮助都将不胜感激,因为我在阅读和搜索元素方面遇到了问题。
目前我正在尝试使用(在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("Documents") 正常返回结果,但是这段代码没有任何返回值。看起来我无法从 Documents 节点中获取 Document 节点。
doc.Descendants("Document")
。 - Andras Zoltan