2016-04-05 4 views
-1

Мне нужно разобрать ниже XML для json в коде C#.Преобразование XML-данных в JSON

<rss version="2.0"> 
<channel> 
<title>TITLE </title> 
<link>http://sample.com/</link> 
<language>en-Us</language> 
<pubDate>System.String[] GMT</pubDate> 
<item> 
<ParentSection>News</ParentSection> 
<ParentSectionTamilname>செய்திகள்</ParentSectionTamilname> 
<ParentSectionID>1</ParentSectionID> 
<Count>6</Count> 
<items> 
<Section>National</Section> 
<Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
<Sectionid>3</Sectionid> 
<SectionURL> 
http://sample.com/rss/RssfeedXML.aspx?Id=3&Main=1 
</SectionURL> 
<SectionJsonURL> 
http://sample.com/json/JsonfeedXML.aspx?Id=3&Main=1 
</SectionJsonURL> 
<subitem> 
<Sub_Count>0</Sub_Count> 
</subitem> 
</items> 
<items> 
<Section>National</Section> 
<Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
<Sectionid>3</Sectionid> 
<SectionURL> 
http://sample.com/rss/RssfeedXML.aspx?Id=3&Main=1 
</SectionURL> 
<SectionJsonURL> 
http://sample.com/json/JsonfeedXML.aspx?Id=3&Main=1 
</SectionJsonURL> 
<subitem> 
<Sub_Count>0</Sub_Count> 
</subitem> 
</items> 
</item> 

<item> 
<ParentSection>News</ParentSection> 
<ParentSectionTamilname>செய்திகள்</ParentSectionTamilname> 
<ParentSectionID>1</ParentSectionID> 
<Count>6</Count> 
<items> 
<Section>National</Section> 
<Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
<Sectionid>3</Sectionid> 
<SectionURL> 
http://sample.com/rss/RssfeedXML.aspx?Id=3&Main=1 
</SectionURL> 
<SectionJsonURL> 
http://sample.com/json/JsonfeedXML.aspx?Id=3&Main=1 
</SectionJsonURL> 
<subitem> 
<Sub_Count>0</Sub_Count> 
</subitem> 
</items> 
<items> 
<Section>National</Section> 
<Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
<Sectionid>3</Sectionid> 
<SectionURL> 
http://sample.com/rss/RssfeedXML.aspx?Id=3&Main=1 
</SectionURL> 
<SectionJsonURL> 
http://sample.com/json/JsonfeedXML.aspx?Id=3&Main=1 
</SectionJsonURL> 
<subitem> 
<Sub_Count>0</Sub_Count> 
</subitem> 
</items> 
</item> 
</channel> 
</rss> 

Ниже приведен мой код на C#, который я использовал для преобразования XML в JSON, но он терпит неудачу. Я не могу сериализовать использование SerializeObject.

var xml = new XmlDocument(); 
       xml.LoadXml(ABOVE XMLSTRING); 
       string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(xml, Newtonsoft.Json.Formatting.None); 

Любая помощь по этому вопросу будет очень высоко ценится ..

Спасибо.

+1

Я не знаю этот сериализатор Json, но я думаю, что вы не можете прямо поставить экземпляр 'XmlDocument' там !? Похоже, он ожидает, что конкретный экземпляр класса со свойствами и значениями будет использоваться как вход. –

+0

Спасибо Ким за ваш ответ – Anbarasi

+1

Попробуйте использовать JsonConvert.SerializeXmlNode (xml) – Kevin

ответ

4

Вам необходимо отформатировать строку XML в соответствии со стандартами XML.

&amp; // Use instead of & 

Форматированная строка XML ниже

<?xml version="1.0" encoding="utf-8" ?> 
<rss version="2.0"> 
    <channel> 
    <title>TITLE </title> 
    <link>http://sample.com/</link> 
    <language>en-Us</language> 
    <pubDate>System.String[] GMT</pubDate> 
    <item> 
     <ParentSection>News</ParentSection> 
     <ParentSectionTamilname>செய்திகள்</ParentSectionTamilname> 
     <ParentSectionID>1</ParentSectionID> 
     <Count>6</Count> 
     <items> 
      <Section>National</Section> 
      <Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
      <Sectionid>3</Sectionid> 
      <SectionURL> 
       http://sample.com/rss/RssfeedXML.aspx?Id=3&amp;Main=1 
      </SectionURL> 
      <SectionJsonURL> 
       http://sample.com/json/JsonfeedXML.aspx?Id=3&amp;Main=1 
      </SectionJsonURL> 
      <subitem> 
       <Sub_Count>0</Sub_Count> 
      </subitem> 
     </items> 
     <items> 
      <Section>National</Section> 
      <Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
      <Sectionid>3</Sectionid> 
      <SectionURL> 
       http://sample.com/rss/RssfeedXML.aspx?Id=3&amp;Main=1 
      </SectionURL> 
      <SectionJsonURL> 
       http://sample.com/json/JsonfeedXML.aspx?Id=3&amp;Main=1 
      </SectionJsonURL> 
      <subitem> 
       <Sub_Count>0</Sub_Count> 
      </subitem> 
     </items> 
    </item> 

    <item> 
     <ParentSection>News</ParentSection> 
     <ParentSectionTamilname>செய்திகள்</ParentSectionTamilname> 
     <ParentSectionID>1</ParentSectionID> 
     <Count>6</Count> 
     <items> 
      <Section>National</Section> 
      <Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
      <Sectionid>3</Sectionid> 
      <SectionURL> 
       http://sample.com/rss/RssfeedXML.aspx?Id=3&amp;Main=1 
      </SectionURL> 
      <SectionJsonURL> 
       http://sample.com/json/JsonfeedXML.aspx?Id=3&amp;Main=1 
      </SectionJsonURL> 
      <subitem> 
       <Sub_Count>0</Sub_Count> 
      </subitem> 
     </items> 
     <items> 
      <Section>National</Section> 
      <Sectiontamil>தேசியச்செய்திகள்</Sectiontamil> 
      <Sectionid>3</Sectionid> 
      <SectionURL> 
       http://sample.com/rss/RssfeedXML.aspx?Id=3&amp;Main=1 
      </SectionURL> 
      <SectionJsonURL> 
       http://sample.com/json/JsonfeedXML.aspx?Id=3&amp;Main=1 
      </SectionJsonURL> 
      <subitem> 
       <Sub_Count>0</Sub_Count> 
      </subitem> 
     </items> 
    </item> 
</channel> 

Вам нужно вызвать метод SerializeXmlNode не сериализовать объект. SerializeObject используется для преобразования xml в экземпляр C#.

Вот код для сериализации XML в JSON с помощью newtonsoft

XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load("InputXml.xml"); // Can use xmlDoc.LoadXml(YourString); 
    string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); 

Это хорошая практика, чтобы сохранить XML в файл и загрузки из файла, а не жесткого кода в виде строки, что делает код неуклюжим.

1

Сначала вы должны исправить свой xml. Его невозможно разобрать. Используйте VS для обнаружения ошибок. Кроме того, у вас есть специальные символы адресов URL, которые вы должны исправить.

4

Вы должны были использовать JsonConvert.SerializeXmlNode() вместо сериализации XML в JSON:

var xml = new XmlDocument(); 
xml.LoadXml("your XML here"); 
string jsonString = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xml);