无法使用XDocument获取元素

本文关键字:获取 元素 XDocument | 更新日期: 2023-09-27 18:03:45

下面是我用来获取'person'的'name'(属性)的值的代码

参数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 '和名称为'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的新手

无法使用XDocument获取元素

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

string info = doc.Descendants(tag).First().Attribute(attribute).Value;