【问题标题】:XML inside of XML NodeXML 节点内的 XML
【发布时间】:2015-03-11 02:55:56
【问题描述】:

我有如下的 XML:

  <CallStep>
    <StepXaml>
      <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:uc="clr-namespace:CallTracker.Library.UserControls.BaseUserControls;assembly=CallTracker.Library">
        <uc:LabelValueControl Label="TestLabel" Value="356733" />
      </StackPanel>
    </StepXaml>
</CallStep>

然后我想存储在一个属性中

[XmlElement("StepXaml")]
public object StepXaml { get; set; }

我正在使用 XmlSerializer 将 XML 反序列化为包含 StepXaml 属性的类。目前,当我反序列化 XML 时,&lt;StackPanel&gt; 正在反序列化到它自己的节点中。

有没有办法防止反序列化器尝试深入了解&lt;StackPanel&gt;,而是将&lt;StepXaml&gt;&lt;/StepXaml&gt; 之间的所有内容作为一个对象返回?

【问题讨论】:

    标签: c# xml xml-deserialization


    【解决方案1】:

    我不确定这是否是您想要的,但如果您像这样为 CallStep 元素定义一个类:

    public class CallStep
    {
        //XmlElement attribute is not needed, because the name of the 
        //property and the XML element is the same
        public XmlDocument StepXaml { get; set; }
    }
    

    然后像这样调用反序列化:

    //xml is a string containing the XML from your question
    XmlSerializer serializer = new XmlSerializer(typeof(CallStep));
    using (StringReader reader = new StringReader(xml))
    {
        CallStep cs = (CallStep)serializer.Deserialize(reader);
    }
    

    那么cs.StepXaml 将是一个包含以下内容的 XmlDocument:

      <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:uc="clr-namespace:CallTracker.Library.UserControls.BaseUserControls;assembly=CallTracker.Library">
        <uc:LabelValueControl Label="TestLabel" Value="356733" />
      </StackPanel>
    

    【讨论】:

      【解决方案2】:

      我通过将 XAML 代码包装在 CDATA 块中来解决此问题,如下所示:

          <StepXaml>
              <![CDATA[<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:uc="clr-namespace:CallTracker.Library.UserControls.BaseUserControls;assembly=CallTracker.Library">
                  <uc:LabelValueControl Label="TestLabel2" Value="356738124315" />
                </StackPanel>]]>
          </StepXaml>
      

      然后我将其提取到一个可以在ContentControl 中使用的对象中,如post 所示

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-06
        • 2018-01-01
        • 1970-01-01
        • 2020-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多