c# - How do I get a string array of these xml values? -


i attempting use linq xml, i'm pretty new it.

this 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> 

i have string value has resource name of need pull out of xml. parameter, example, might "brandinfo_bbb". , need return string array containing of hosts block. can linq xml?

first of all: load xml xdocument object , prepare result variable:

var doc = xdocument.load("input.txt"); string[] hosts; 

then can query document. i assumed resourcename unique across input 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(); } 

for non-unique 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(); } 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -