1

我试图使用 linq to 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 to xml 做到这一点吗?

4

3 回答 3

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();
}
于 2013-04-05T20:33:38.903 回答
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();
于 2013-04-05T20:45:18.667 回答
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();
于 2013-04-05T21:03:03.697 回答