2011-01-13 121 views
1

如果我有以下XML,我將如何使用LINQ to XML消除每個視頻節點中的日期字段?我想在單元測試中進行比較。LINQ to XML選擇/更新

<?xml version="1.0" encoding="utf-8" standalone="yes" ?> 
<main> 
<videos> 
    <video> 
     <id>00000000-0000-0000-0000-000000000000</id> 
     <title>Video Title</title> 
     <videourl>http://sample.com</videourl> 
     <thumbnail>http://sample.com</thumbnail> 
     <dateCreated>2011-01-12T18:54:56.7318386-05:00</dateCreated> 
     <dateModified>2011-02-12T18:54:56.7318386-05:00</dateModified> 
     <Numbers> 
      <Number>28</Number> 
      <Number>78</Number> 
     </Numbers> 
    </video> 
    <video> 
     <id>00000000-0000-0000-0000-000000000000</id> 
     <title>Video Title</title> 
     <videourl>http://sample.com</videourl> 
     <thumbnail>http://sample.com</thumbnail> 
     <dateCreated>2011-01-12T18:54:56.7318386-05:00</dateCreated> 
     <dateModified>2011-02-12T18:54:56.7318386-05:00</dateModified> 
     <Numbers> 
      <Number>28</Number> 
      <Number>78</Number> 
     </Numbers> 
    </video> 
</videos> 
+0

請再次格式化您的代碼,我看不到XML但純文本。 – xandy 2011-01-13 00:45:29

回答

2

如果你只是想清除節點的內容:

// Load the XML document 
XDocument doc = ...; 

// Select the date nodes 
var query = doc.Descendants() 
       .Where(e => e.Name.LocalName.StartsWith("date")); 

// Clear the contents of each 
foreach (var element in query) 
{ 
    element.SetValue(String.Empty); 
} 

// Optionally write it back 
doc.Save(...); 

產量:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<main> 
    <videos> 
    <video> 
     <id>00000000-0000-0000-0000-000000000000</id> 
     <title>Video Title</title> 
     <videourl>http://sample.com</videourl> 
     <thumbnail>http://sample.com</thumbnail> 
     <dateCreated></dateCreated> 
     <dateModified></dateModified> 
     <Numbers> 
     <Number>28</Number> 
     <Number>78</Number> 
     </Numbers> 
    </video> 
    <video> 
     <id>00000000-0000-0000-0000-000000000000</id> 
     <title>Video Title</title> 
     <videourl>http://sample.com</videourl> 
     <thumbnail>http://sample.com</thumbnail> 
     <dateCreated></dateCreated> 
     <dateModified></dateModified> 
     <Numbers> 
     <Number>28</Number> 
     <Number>78</Number> 
     </Numbers> 
    </video> 
    </videos> 
</main> 

不幸的是它會修改所有日期節點無論身在何處,他們都在你的XML。我個人更喜歡在上面使用XPath查詢,如果給出的選項非常明確,哪些節點應該更新。使用純粹的LINQ to XML也可以做到這一點,但它不如此優雅。

var xpath = "/main/videos/video/*[starts-with(name(.),'date')]"; 
var query = doc.XPathSelectElements(xpath);