C# parse XML from HTML Body and save to file

Viewed 122

C# after performing GET from the API it returns the XML code embedded in the HTML file similar to this:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta name="viewport" content="initial-scale=1, width=device-width">
        <title>config</title>
    </head>
    <body>
        
<CONFIG="2"/>
<VALUE1="1"/>
<VALUE2="2"/>
<CONFIGEND="0"/>

    </body>
</html>

I am trying to save the XML content from the body "<CONFIG ... CONFIGEND="0"/>" out to a file. My attempts using HtmlAgilityPack result in the XML data being modified as follows:

<CONFIG="2"></CONFIG>
...
<CONFIGEND="0"></CONFIGEND>

I am new to C# (and programming in general) so please be kind. Search attempts have left me more confused than I started :/

2 Answers

Yes you have figured out HtmlAgilityPack is converting something. Html actually an Xml file. But System.Xml.XmlDocument cannot handle this html file. So you need to parse manually.

As Anis R. says, best way is RegularExpressions. To use RegularExpressions, you need to add using System.Text.RegularExpressions; to first lines.

Let's say your Html content is in htmlstring variable.

Firstly you need to define pattern for your case.

string regexPattern = @"\<body\>(.*?)\<\/body\>";
Regex regex = new Regex(regexPattern, RegexOptions.Singleline);

You need to use RegexOptions.Singleline option. Because your html content will have new line characters.

string body = regex.Match(htmlstring).Value;

With this, you will have :

<body>
        
<CONFIG="2"/>
<VALUE1="1"/>
<VALUE2="2"/>
<CONFIGEND="0"/>

    </body>

To remove body tags ;

string result = body.Replace("<body>", "").Replace("</body>", "");

To trim leading and trailing spaces;

string prettierResult = result.Trim();

Now you have ;

<CONFIG="2"/>
<VALUE1="1"/>
<VALUE2="2"/>
<CONFIGEND="0"/>

To save content to a file ;

File.WriteAllText("c:\\path-to-save", prettierResult);

If the format is consistent1 (e.g., you always want everything between <body>...</body>), then one way is to use a regex:

string pattern = @"<body>(.*)</body>";  
Regex rg = new Regex(pattern);  
        
string html = "<body>Content here</body>";  
        
// get first match and print it
Match firstMatch = rg.Matches(html)[0];
Console.WriteLine(firstMatch.Groups[1]); // "Content here" 

(PS: this will need using System.Text.RegularExpressions;)


1 Keeping this in mind

Related