如何获取这些xml值的字符串数组?

时间:2013-04-05 20:26:20

标签: c# .net xml linq-to-xml

我试图将linq用于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 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();

答案 2 :(得分: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永远不会为空,因此立即使用它总是安全的......

string[] vals = hosts.ToArray();