【问题标题】:Not able to get the element with XDocument无法使用 XDocument 获取元素
【发布时间】:2013-03-14 07:41:52
【问题描述】:

下面是我用来获取“人”的“名称”(属性)值的代码

参数标签=“人”和参数属性=“名称”

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 时,它确实有一个类型为“元素”且名称为“人”的元素 正在读取的文件是 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 的新手!

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢,我想确认一下,如果我必须在嵌套标签内进入任何级别,我想我将不得不一直这样做 doc.Descendents(a).Descendents(b )....等等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多