jjzjj

c# - 带有嵌套标签的 Xml 反序列化不起作用

coder 2024-06-27 原文

我需要将一个 XML 文件反序列化为一个对象。以下是 XML 内容:

<?xml version="1.0" encoding="utf-8" ?>
<PdfFile>
  <PageTitle DocumentName="Sequence Diagram" Version="Version 4" >Title</PageTitle>
  <LogoPath>C:\logo.png</LogoPath>
  <Modules>
    <Module Id="1" MainTitle="Module1">
      <SubModules>
        <SubModule>
          <Title>SubModule1</Title>
          <Path>SubModule1 Path</Path>
          <Description>SubModule1 Desc</Description>
        </SubModule>
        <SubModule>
          <Title>SubModule2</Title>
          <Path>SubModule2 Path</Path>
          <Description>SubModule2 Desc</Description>
        </SubModule>
      </SubModules>
    </Module>
    <Module Id="2" MainTitle="Module2">
      <SubModules>
         <SubModule>
           <Title>SubModule1</Title>
           <Path>SubModule1 Path</Path>
           <Description>SubModule1 Desc</Description>
         </SubModule>
      </SubModules>
    </Module>
  </Modules>
</PdfFile>

以下是我为上述 xml 文件创建的类文件。

    using System;
    using System.Xml.Serialization;

    namespace PDFCreation.Objects
    {

        [Serializable]
        [XmlRoot("PdfFile")]
        public class PdfFile2
        {
            [XmlElement("PageTitle")]
            public PageTitle FirstPage { get; set; }

            [XmlElement("LogoPath")]
            public string LogoPath { get; set; }

            [XmlArray("Modules")]
            [XmlArrayItem("Module", typeof(Module))]
            public Module[] Modules { get; set; }

        } 

        [Serializable]
        public class Module
        {
            [XmlAttributeAttribute("Id")]
            public int Id { get; set; }

            [XmlAttributeAttribute("MainTitle")]
            public string MainTitle { get; set; }

            [XmlArray("SubModules")]
            [XmlArrayItem("SubModule", typeof(SubModule))]
            public SubModule[] Modules { get; set; }
        } 

        [Serializable]
        public class SubModule
        {
            [XmlElement("Title")]
            public string Title { get; set; }

            [XmlElement("Path")]
            public string Path { get; set; }

            [XmlElement("Description")]
            public string Description { get; set; }
        }

        [Serializable]
        public class PageTitle
        {
            [XmlText]
            public string Title { get; set; }

            [XmlAttribute]
            public string DocumentName { get; set; }

            [XmlAttribute]
            public string Version { get; set; }
        }

     }

在反序列化时,我没有收到任何错误。但是 PdfFile 对象中的模块总是返回 null。我尝试使用 xsd.exe 生成的类。但同样的事情仍在发生。

请帮我找出代码/xml 中的问题以及为什么它没有完全反序列化?

谢谢!!!

编辑:

我的 C# 代码:

  public class Program
{
    private static readonly string XmlPath = ConfigurationManager.AppSettings["XmlPath"];

    static void Main(string[] args)
    {
        try
        {
            ReadXml();
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
            Console.ReadLine();
        }
    }

    private static void ReadXml()
    {
        if (!File.Exists(XmlPath))
        {
            Console.WriteLine("Error: Xml File Not exists in the path: {0}", XmlPath);
            return;
        }

        using (var reader = new StreamReader(XmlPath))
        {
            var serializer = new XmlSerializer(typeof(PdfFile2));
            var result = (PdfFile2)serializer.Deserialize(reader);

            //other code here
        }
    }
}

最佳答案

只使用您提供的代码/xml 并放入缺少的结束标记,我使用此主类将其反序列化:

using System.IO;
using System.Xml.Serialization;
using PDFCreation.Objects;

public class Test
{
    static void Main(string[] args)
    {
        XmlSerializer ser = new XmlSerializer(typeof(PdfFile2));
        PdfFile2 pdf = (PdfFile2)ser.Deserialize(File.OpenRead("test.xml"));
    }
}

你的反序列化代码是什么样的?

关于c# - 带有嵌套标签的 Xml 反序列化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9991813/

有关c# - 带有嵌套标签的 Xml 反序列化不起作用的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  3. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  4. ruby - 在院子里用@param 标签警告 - 2

    我试图使用yard记录一些Ruby代码,尽管我所做的正是所描述的here或here#@param[Integer]thenumberoftrials(>=0)#@param[Float]successprobabilityineachtrialdefinitialize(n,p)#initialize...end虽然我仍然得到这个奇怪的错误@paramtaghasunknownparametername:the@paramtaghasunknownparametername:success然后生成的html看起来很奇怪。我称yard为:$yarddoc-mmarkdown我做错了什么?

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  7. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  8. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  9. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  10. ruby-on-rails - 使用回形针的嵌套形式 - 2

    我有一个名为posts的模型,它有很多附件。附件模型使用回形针。我制作了一个用于创建附件的独立模型,效果很好,这是此处说明的View(https://github.com/thoughtbot/paperclip):@attachment,:html=>{:multipart=>true}do|form|%>posts中的嵌套表单如下所示:prohibitedthispostfrombeingsaved:@attachment,:html=>{:multipart=>true}do|at_form|%>附件记录已创建,但它是空的。文件未上传。同时,帖子已成功创建...有什么想法吗?

随机推荐