无法使用XDocument获取元素

时间:2013-03-14 07:41:52

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

以下是我用于获取“人物”的“名称”(属性)值的代码

参数tag =“person”和参数attribute =“name”

public static string GetInformationFromXML(string tag,
                                           string attribute,
                                           string filePath)
{
        XDocument doc = XDocument.Load(filePath);
        string info = doc.Element(tag).Attribute(attribute).Value;

        return info;
}

doc.Element(tag)没有得到元素,即使我扩展doc时,它确实有一个元素类型为'Element'且Name'person' 正在读取的文件是XmlDocument以供参考。

下面的

是我试图阅读的文件的xml

<?xml version="1.0"?>
<import>
  <company name1="ABC" name2="" action="create" 
           profile="\Profiles\ABC\" id="C1">
    <address street="industrial" city="london" 
             country="england" id="A1">
      <telecom type="phone" value="4839282992" 
               desc="" default="true" />
      <telecom type="fax" value="3232" desc="" />
    </address>
  </company>
  <person title="Mr." name="Tariq" surname="sheikh" 
          lang="EN" action="create"  profile="Profiles\Tariq" 
          login="tariq" password="123456" default_address="A1">
    <link reference="C1" type="Employee" description="Software developer" />
    <address street="baker street" zip="12443" 
             city="london" country="england" />
    <account bank="Barclays" account="4378734834" />
    <telecom type="email" value="tariq.sheikh@abc.co.in" desc="" />
    <registration type="temporaryID" 
                  value="4623648c-739e-49c8-93fa-41dc7fed53ea" />
  </person>
</import>

我是XDocument的新手!

1 个答案:

答案 0 :(得分:0)

当您要查找的元素不是当前元素的直接子元素(或Descendants的根)时,您必须使用XDocument

string info = doc.Descendants(tag).First().Attribute(attribute).Value;
相关问题