简体   繁体   中英

How to Get a specific Value of an XML Node from XDocument

I am asking essentially the same question as found in this post: How to Get XML Node from XDocument with the exception of attempting to do a one-shot return of the CData value in a single line of code. I'm attempting to get the return in the below function to work properly:

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

I have the following XML below:

<?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>

I know I'm doing this incorrectly, and was hoping to get a larger set of eyes on it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM