2012-04-13 23 views
2

我很積極,這是一個簡單的問題,但我無法弄清楚。通過搜索'name'來檢索元素'值'

我下載一個XML文件在C#中的字符串,它包含以下格式項:

<attribute name="Make" value="Volvo" /> 
<attribute name="Color" value="Blue" /> 
<attribute name="Damage" value="Rear scratched" /> 
<attribute name="Damage" value="Left hand side dented" /> 

所有我想要做的就是價值觀的所有爲「損害「在整個文檔中(不管它們落在哪裏)放入一個數組中。我一直在玩XmlDocument/XmlNodeList,但我無法弄清楚如何讓這個工作。

我一半想用RegEx來做,但感覺非常髒。

+0

使用Linq XML =快速和容易閱讀的代碼。 http://msdn.microsoft.com/en-us/library/bb387098.aspx – Sogger 2012-04-13 15:37:37

+0

請不要用「XML/C#」等標題來標題。這就是標籤的用途。 – 2012-04-13 16:07:04

回答

7

使用XDocument

var doc = XDocument.Parse(xml); 
var result = doc.Descendants("attribute") 
       .Where(x => x.Attribute("name") != null && 
          x.Attribute("value") != null) 
       .Where(x => x.Attribute("name").Value == "Damage") 
       .Select(x => x.Attribute("value").Value) 
       .ToArray(); 

請注意:
此代碼是相對簡單的,因爲它需要整個文檔中的所有節點attribute考慮。

+1

caveat:問題中的屬性列表將不會與此代碼「按原樣」一起使用。沒有「根元素」。如果「屬性」元素有一個父「屬性」元素,那麼這個代碼示例完美地工作。 – 2012-04-13 15:25:52

+0

@GlennFerrieLive:這對代碼沒有問題,但是提供了示例數據,因爲這根本就不是有效的XML,我認爲OP僅顯示相關部分。 – 2012-04-13 15:26:49

+0

我同意你的意見。 – 2012-04-13 15:36:16

1
string val = ""; 
XmlDocument doc = new XmlDocument(); 

doc.Load("file.xml"); 

XmlNodeList nodes = doc.SelectNodes("/attribute[@name='Damage']"); 

foreach (XmlNode node in nodes) 
{ 
    { 
     val = node.Attributes["value"].Value; 
    } 
} 

應該工作嗎?

+1

對不起,代碼已被編輯 – 2012-04-13 15:39:34

+0

@DanielHilgarth代碼自我原來的評論被編輯,我現在將刪除,以響應編輯修復。 – Sogger 2012-04-13 15:53:38

1

你可以利用LINQ-TO-XML,但是你必須爲它提供一個很好的XML,所以只需手動創建一個根節點,否則你將以System.Xml.XmlException : There are multiple root elements.結束。

// raw - your XML 
string raw = File.ReadAllText("c:\\test1.xml"); 

// create root node manually 
string xml = "<root>" + raw + "</root>"; 
var xdoc = XDocument.Parse(xml);  

// contains IEnumerable<string> 
// TODO: add null-checks 
var damagedValues = xdoc.Descendants("attribute") 
         .Where(e => e.Attribute("name").Value == "Damage") 
         .Select(e => e.Attribute("value").Value); 
1

那麼,這不是一個XML文檔,它是一個片段。你需要用一個根元素來包裝它。這將工作:

string fragment = File.ReadAllText("file.xml"); 
var doc = XDocument.Parse("<root>" + fragment + "</root>"); 

var values = from element in doc.XPathSelectElements(@"//attribute[@name='Damage']") 
      select element.Attribute("value").Value; 

values.ToList().ForEach(Console.WriteLine);