【问题标题】:Getting section filtering to xml attribute获取部分过滤到 xml 属性
【发布时间】:2012-03-28 12:16:13
【问题描述】:

我想根据短信xml的tip属性选择短信段块。 目前:ConfigurationManager.GetSection("Logger/Sms") 有效,但有没有办法获得像ConfigurationManager.GetSection("Logger/Sms[@tip='VF']") 这样的部分?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="Logger">
      <section name="Sms" type="caSectionTest.LogHandler, caSectionTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </sectionGroup>
  </configSections>

  <Logger>
    <Sms tip="Clickatell">
      <icerik>Soğuk zincir uygulamasından gönderilen sms</icerik>
      <telNo>9053123123123</telNo>
      <api>3363050</api>
      <user>pkUser</user>
      <pass>passhm</pass>
    </Sms>
    <Sms tip="Vodafone">
      <icerik>write something into sms</icerik>
      <telNo>905123123123</telNo>
      <originator>336123</originator>
      <user>ctUser</user>
      <pass>9Mdfpass</pass>
    </Sms>
  </Logger>
</configuration>

【问题讨论】:

  • 我使用的一个技巧是抓取整个部分...然后将 xml 反序列化为一个对象。然后您可以使用该对象来获取您的配置项,而您没有弄乱那个疯狂的语法。
  • 你确定这行得通吗?当我尝试从web.configapp.config 文件中获取此信息时,我收到Sections must only appear once per config file. See the help topic &lt;location&gt; for exceptions. 错误。您能否更新问题以包含有关如何重现此问题的说明?

标签: c# xml configurationsection


【解决方案1】:

你可能早就离开了,但我为最近可用的 xml XElement 创建了一个 XPath 查找:https://github.com/ChuckSavage/XmlLib/ 如果你想使用 jsobo 的评论来获取你想要的信息。

你会像这样使用它:

XElement root = XElement.Load(file);
XElement sms = root.XPathElement("//Sms[@tip={0}]", "VF"); // or "//Sms[@tip='VF']"

通过将它与 string.Format() 语法一起使用,如果你想进行 DateTime 检查等,你也可以将类型传递给 XPath。我还发现变量注入也更容易,而不是 @987654323 @。 XPathElement 只需XPath().FirstOrDefault() 即可返回单个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 2013-06-07
    • 2011-02-11
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多