2012-07-06 100 views
6

我确信这是基本的,可能之前曾被问到过,但我只是开始使用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( “文档”)一样。它看起来像我不能从文档节点获取文档节点。

回答

7

您可以在下面的代码中找到那些文档(索引数据中没有相关名称的文档),之后您可以将元素添加到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); 
+0

我认为这应该是'doc.Descendants( “文档”)' – 2012-07-06 06:36:52

+0

谢谢,固定。 – 2012-07-06 06:41:26

0

这应该工作:

var x = XDocument.Load(filePath); 
// guid in your sample xml is not a valid guid, so I changed it to a random valid one 
var requiredGuid = new Guid("E61D174C-9048-438D-A532-17311F57ED9B"); 
var requiredName = "Name1"; 

var doc = x.Root 
      .Elements("Document") 
      .Where(d => (Guid)d.Element("GUID") == requiredGuid) 
      .FirstOrDefault(); 
if(doc != null) 
{ 
    var data = doc.Element("IndexDatas") 
        .Elements("IndexData") 
        .Where(d => (string)d.Element("Name") == requiredName) 
        .FirstOrDefault(); 
    if(data != null) 
    { 
     // index data found 
    } 
    else 
    { 
     // index data not found 
    } 
} 
else 
{ 
    // document not found 
} 
+0

你好。我知道GUID是错误的,但应该视为简单的字符串。但我没有收到任何文件(doc为空)! – no9 2012-07-06 08:51:31