我如何解析这种格式化的XML?

时间:2017-03-17 12:26:44

标签: c# .net xml xml-parsing .net-4.6

这是我从外部来源获得的当前格式

<d:entry id="_qkq" d:title="DuMont Television Network">
        <d:index d:value="DuMont Television Network" d:title="DuMont Television Network"/>
        <d:index d:value="dumont tv" d:title="DuMont Television Network"/>
        <d:index d:value="dumont network" d:title="DuMont Television Network"/>
        <h1>DuMont Television Network</h1>
       some value etc 
</d:entry>

如果它像下面那样我可以很容易地解析它。所以任何想法我如何解析它如下或将其转换为以下格式?

<entry>
   <entryId>_qkq</entryId>
   <entryTitle>DuMont Television Network</entryTitle>
   <entryIndex>
      <value>DuMont Television Network</value>
      <title>DuMont Television Network</title>
   </entryIndex>
   <entryIndex>
      <value>dumont tv</value>
      <title>DuMont Television Network</title>
   </entryIndex>
   <entryIndex>
      <value>dumont network</value>
      <title>DuMont Television Network</title>
   </entryIndex>
   <entryValue>
      <h1>DuMont Television Network</h1>
      some value etc
   </entryValue>
</entry>

非常感谢您的回答

1 个答案:

答案 0 :(得分:2)

好的,这很容易,可以通过很多方式完成,但是为了便于开发:

  1. 为此XML生成类 - 在Visual Studio中,创建新的代码文件。将完整的XML复制到剪贴板中。点击Edit-paste special - Paste XML as classes
    这将为您提供必要的类,其根目录为dictionary。 (如果你想我可以添加生成的列表)
  2. 然后,在任何必要的文件中,您可以执行以下操作:

      var data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \r\n<d:dictionary xmlns=\"w3.org/1999/xhtml\" xmlns:d=\"apple.com/DTDs/DictionaryService-1.0.rng\">\r\n\t<d:entry id=\"_qkq\" d:title=\"DuMont Television Network\">\r\n\t\t<d:index d:value=\"DuMont Television Network\" d:title=\"DuMont Television Network\"/>\r\n\t\t<d:index d:value=\"dumont tv\" d:title=\"DuMont Television Network\"/>\r\n\t\t<d:index d:value=\"dumont network\" d:title=\"DuMont Television Network\"/>\r\n\t\t<h1>DuMont Television Network</h1>\r\n\t</d:entry>\r\n</d:dictionary>";
    
      XmlSerializer serializer = new XmlSerializer(typeof(dictionary));
      using (TextReader reader = new StringReader(data))
      {
        dictionary result = (dictionary)serializer.Deserialize(reader);
      }
    
  3. result现在包含您的数据:

    screenshot