如何从XDocument获取XML节点的特定值

本文关键字:节点 XML XDocument 获取 | 更新日期: 2023-09-27 17:55:43

我问的问题基本上与这篇文章中发现的问题相同:如何从XDocument获取XML节点,除了尝试在一行代码中一次性返回CData值。 我正在尝试让以下函数中的返回正常工作:

private string RetrieveFormattedString(string controlId)
{
    return template.Descendants("Template")
      .Where(templateNode => templateNode.Value == controlId)
      .Where(tmp => tmp.Name == "Format").Select(y => y.Value).ToString();
}

我有以下 XML:

<?xml version="1.0" encoding="utf-8" ?>
  <Templates>
    <Template>
      <Name>NodeName1</Name>
        <Parameter Type="TextBox" Name="conferenceID">{__otcConferenceID__}</Parameter>
        <Parameter Type="TextBox" Name="conferenceCode">{__otcConferenceCode__}</Parameter>
        <Format>
          <![CDATA[ <b>NodeName1</b><br /> <table><tr><td>iPhone</td><td>{__otcConferenceID__},#,{__otcConferenceCode__}</td></tr></table>]]>
        </Format>
     </Template>
     <Template>
        <Name>NodeName2</Name>
        <Parameter Type="TextBox" Name="conferenceID">{__otcConferenceID__}</Parameter>
        <Parameter Type="TextBox" Name="conferenceCode">{__otcConferenceCode__}</Parameter>
        <Format>
            <![CDATA[ <b>NodeName2</b><br /> <table><tr><td>iPhone</td><td>{__otcConferenceID__},#,{__otcConferenceCode__}</td></tr></table>]]>
        </Format>
    </Template>
</Templates>

我知道我做错了,并希望得到更多的关注。

如何从XDocument获取XML节点的特定值

private string RetrieveFormattedString(XDocument xDoc, string nodeName)
{
    return xDoc.Descendants("Template")
                .First(t => t.Element("Name").Value == nodeName)
                .Element("Format").Value;
}