【问题标题】:Set a constructor-arg of type XmlElement from XML Spring.NET IoC config从 XML Spring.NET IoC 配置中设置 XmlElement 类型的构造函数参数
【发布时间】:2011-05-20 09:01:41
【问题描述】:

想象一下:

class Foo {
  public Foo(XmlElement xml) { ... }
}

我想使用 Spring.NET 和 XmlApplicationContext 实例化这个类。 生成 XmlElement 的 XML 应该包含在 XmlApplicationContext 配置文件中,以便于编辑。

所以它应该看起来像这样:

<objects>
  <object id="foo" type="Foo, Foo">
    <constructor-arg name="xml" ???>
      <???>
        <element1 attr="bla" />
        <element2 xyz="abc>
          <... />
        </element2>
      </???>
    </constructor-arg>
  </object>
</objects>

元素??>应该是注入的XmlElement。

有什么办法可以做到吗?

我知道我可以传递一个文件名并手动加载内部 XML。如果没有其他办法,这将是解决方案。但为了方便用户,我最喜欢“嵌入式 XML”解决方案 :-)

【问题讨论】:

    标签: c# xml spring.net


    【解决方案1】:

    您可以使用static factory&lt;![CDATA[ ... ]]&gt;

    public static class XmlElementFactory
    {
        public static XmlElement Create(string value)
        {
            var doc = new XmlDocument();
            doc.LoadXml(value);
            return doc.DocumentElement;
        }
    }
    
    public class Foo
    {
        private readonly XmlElement _xml;
        public Foo(XmlElement xml)
        {
            _xml = xml;
        }
    
        public override string ToString()
        {
            return _xml.OuterXml;
        }
    }
    
    class Program
    {
        static void Main()
        {
            var foo = (Foo)ContextRegistry.GetContext().GetObject("foo");
            Console.WriteLine(foo);
        }
    }
    

    在配置文件中:

    <configuration>
      <configSections>
        <sectionGroup name="spring">
          <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
          <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
      </configSections>
    
      <spring>
        <context>
          <resource uri="config://spring/objects"/>
        </context>
    
        <objects xmlns="http://www.springframework.net">
          <object id="foo" type="MyNs.Foo">
            <constructor-arg name="xml">
              <object type="MyNs.XmlElementFactory" factory-method="Create">
                <constructor-arg name="value">
                  <value>
                    <![CDATA[
                    <root>
                      <element1 attr="bla" />
                      <element2 xyz="abc">
                      </element2>
                    </root>
                    ]]>
                  </value>
                </constructor-arg>
              </object>
            </constructor-arg>
          </object>
        </objects>
      </spring>  
    </configuration>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多