简体   繁体   English

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

[英]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. 我问的是与本文中发现的问题基本相同的问题: 如何从XDocument获取XML节点,但尝试在单行代码中一次性返回CData值。 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:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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