2013-04-05 54 views
1

我正在嘗試使用LINQ到XML,但我很新。如何獲得這些xml值的字符串數組?

這是XML:

<BrandHosts> 
    <Brand> 
    <ResourceName>BrandInfo_AAA</ResourceName> 
    <Hosts> 
     <Host>www.aaa.com</Host> 
     <Host>portal.aaa.com</Host> 
     <Host>aaa.com</Host> 
    </Hosts> 
    </Brand> 
    <Brand> 
    <ResourceName>BrandInfo_BBB</ResourceName> 
    <Hosts> 
     <Host>www.bbb.com</Host> 
     <Host>bbb.com</Host> 
     <Host>portal.bbb.com</Host> 
    </Hosts> 
    </Brand> 
    <Brand> 
    <ResourceName>BrandInfo_CCC</ResourceName> 
    <Hosts> 
     <Host>www.CCC.com</Host> 
    </Hosts> 
    </Brand> 
    <Brand> 
    <ResourceName>BrandInfo_DDD</ResourceName> 
    <Hosts> 
     <Host>www.DDD.com</Host> 
    </Hosts> 
    </Brand> 
</BrandHosts> 

我將有什麼,我需要拔出這個XML的資源名稱的字符串值。所以我的參數可能是「BrandInfo_BBB」。我需要返回一個包含該塊中所有主機的字符串數組。我可以用linq到xml來做到這一點嗎?

回答

3

首先:加載XML到XDocument對象和準備的結果變量:

var doc = XDocument.Load("Input.txt"); 
string[] hosts; 

然後你就可以查詢該文檔。 我認爲ResourceName在輸入XML中是唯一的。

var resourceName = "BrandInfo_DDD"; 

var brand = doc.Root.Elements("Brand").SingleOrDefault(b => (string)b.Element("ResourceName") == resourceName); 

if (brand != null) 
{ 
    hosts = brand.Element("Hosts") 
       .Elements("Host") 
       .Select(h => (string)h) 
       .ToArray(); 
} 

對於非唯一ResourceName

var brands = doc.Root.Elements("Brand").Where(b => (string)b.Element("ResourceName") == resourceName).ToArray(); 

string[] hosts; 

if (brands.Length > 0) 
{ 
    hosts = brands.SelectMany(b => b.Element("Hosts") 
            .Elements("Host") 
            .Select(h => (string)h) 
            ).ToArray(); 
} 
+0

繁榮。好的謝謝! – Sinaesthetic 2013-04-05 20:41:56

1
string toSearch = "BrandInfo_BBB"; 

XDocument xDoc = XDocument.Load("XMLFile1.xml"); 


string[] strArr = xDoc.Descendants("Brand").Where(n => n.Element("ResourceName").Value == toSearch).Single() 
         .Descendants("Host").Select(h => h.Value).ToArray(); 
+0

這取決於它應該的。起初我正在嘗試'後裔(「ResourceName」)',這是錯誤的 – 2013-04-05 20:45:54

1

只是提供另一種選擇......

XDocument doc = XDocument.Load("BrandHosts.xml"); 
string resourceName = "BrandInfo_DDD"; 

var resources = doc 
    .Descendants("Brand") 
    .Where(n => n.Element("ResourceName").Value == resourceName); 

var hosts = resources.Any() ? 
    resources.Descendants("Host").Select(h => h.Value) : 
    Enumerable.Empty<string>(); 

通過上述使用Enumerable.Empty<>(當沒有返回資源)您確保hosts永遠不會爲null a因此它立即使用它總是安全的...

string[] vals = hosts.ToArray(); 
相關問題