Home > other >  How to insert href into json in c#
How to insert href into json in c#

Time:10-23

My problem is following previous question: Save JSON with Custom Column name and custom value
Have this code so far

Dictionary<string, object> myDict = new Dictionary<string, object>();
foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']"))
{
    foreach (var row in table.SelectNodes("tbody/tr"))
    {
        var cells = row.SelectNodes("td");
        myDict.Add(cells[0].InnerText, cells[1].InnerText);
    }
}
var json = JsonConvert.SerializeObject(myDict, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);

There are only 2 a href in that table.

Using Newtonsoft.Json, HtmlAgilityPack
I have this table

<table>
    <tr>
        <td>Column1</td>
        <td><a href="http://link.com/files/test.pdf">Value1</a></td>
    </tr>
    <tr>
        <td>Column2</td>
        <td>Value2</td>
    </tr>
    <tr>
        <td>Column3</td>
        <td valign="top" class="ms-formbody" width="450px" id="SPFieldUser">
        <nobr><span><a onclick="GoToLink(this);return false;" href="http://link.com/User/Test.php">Value3</a><img src="blank.gif"><a href="javascript:" onclick="IMNImageOnClick();return false;" class="ms-imnlink"</a></span></nobr></td>
    </tr>
    <tr>
        <td>Column4</td>
        <td>Value4</td>
    </tr>
</table>

And I want to get JSON Output like this

{
  "Column1": "Value1",
  "Column2": "Value2",
  "Column3": "Value3",
  "Column4": "Value4",
  "PDF": "http://link.com/files/test.pdf",
  "User": "http://link.com/User/Test.php"
}

CodePudding user response:

How about...

Dictionary<string, object> myDict = new Dictionary<string, object>();
foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']"))
{
    foreach (var row in table.SelectNodes("tbody/tr"))
    {
        var cells = row.SelectNodes("td");
        myDict.Add(cells[0].InnerText, cells[1].InnerText);
                    
        foreach(var cell in cells)
        {
            var anchorTags = cell.SelectNodes(".//a");
            if (anchorTags == null) continue;

            foreach(var anchorTag in anchorTags)
            {
                var href = anchorTag.Attributes["href"];
                if (href == null) continue;

                // probably will want to create a function that extracts
                // the key from the URL using RegEx or something
                var key = string.Empty;
                if (href.Value.Contains("/files/")) key = "PDF";
                if (href.Value.Contains("/User/")) key = "User";

                myDict.Add(key, href.Value);
            }
        }
    }
}
var json = JsonConvert.SerializeObject(myDict, Newtonsoft.Json.Formatting.Indented);
  • Related