no9*_*no9 6 c# xml linq linq-to-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>
Run Code Online (Sandbox Code Playgroud)
我有一个"文档"节点,其中包含一堆"文档"节点.
我有文档的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();
Run Code Online (Sandbox Code Playgroud)
编辑
xmlDocuments.Element("Documents").Elements("Document")
Run Code Online (Sandbox Code Playgroud)
即使xmlDocuments.Element("Documents")也没有返回结果.看起来我无法从Documents节点获取Document节点.
您可以使用以下代码找到那些文档(索引数据中没有相关名称的文档),之后您可以将元素添加到IndexData元素的末尾.
var relatedDocs = doc.Elements("Document")
.Where(x=>x.Element("GUID").Value == givenValue)
.Where(x=>!x.Element("IndexDatas")
.Elements("IndexData")
.Any(x=>x.Element("Name") == someValue);
Run Code Online (Sandbox Code Playgroud)