简体   繁体   中英

Read cdata and html inside a tag by linqToXml

I want to get rid of CDATA and i want to read the br tag. this is my xml :

<body>
<![CDATA[
Apple iPhone är mycket mer än en mobil. Den är en kombination av tre enheter: en       revolutionerande mobiltelefon, en iPod i widescreenformat och en banbrytande Internetenhet.  Allt detta och mer därtill gör den till den bästa mobiltelefon du kan föreställa dig.
]]>
<br/>
<![CDATA[
Med de maskinvarufunktionerna i iPhone i kombination med världens mest avancerade   mobiloperativsystem öppnar Apple möjligheter för vad en mobiltelefon kan göra. Programmen   är helt integrerade med varandra och kan synkroniseras med din dator - oavsett om du   använder Mac eller PC. Från Multi-Touch-skärmen till det smarta tangentbordet och   sensorerna.
]]>
<br/>
</body>

and here is my code :

 public static List<string> GetDescriptionXml(string idItem)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        XDocument xdoc = XDocument.Load(GetDescription(idItem));
        return (from doc in xdoc.Elements("body") select doc.Value).ToList();
    }

When I run this I just get the value inside the CDATA without the br tag! I can i get the br tag too ?

The ultimate solution depends on all possible cases your HTML may contain. This is one possible solution :

.....
return (from doc in xdoc.Elements("body")
        select string.Join(Environment.NewLine,
                           doc.Nodes()
                              .Select(o =>
                                      {
                                        if (o is XCData) return ((XCData)o).Value;
                                        else return o.ToString();
                                      }))
        ).ToList();

This solution joins all child nodes of the <body> by line break. For each child node, if it is a CData section the value will be taken for String.Join() operation. Else, if it is <br/> or anything other than CData the entire markup will be taken.

In case you want to treat other child nodes type differently, you can easily modify the if ... else ... part according to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM