Click here to Skip to main content
15,894,343 members
Articles / Programming Languages / XML
Tip/Trick

Simply Getting a Value from XML or JSON

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
8 May 2019CPOL1 min read 8.2K   135   3   5
Sometimes, I wanted to know that I did write the right path for getting a single value from XML or JSON string. So, I made a simple program like this.

Introduction

I can't remember the whole grammars for XPath or JPath. When I need it as necessary, then I have been looking for the right path strings on the internet. So, I wanted to know that I'm writing the right path for getting a single value from my XML or JSON string. So, I made a simple program for test like this.

Background

I know you already know the XML and JSON format though, if you do not, you should study it first. :) XML format is composed of nodes surrounded by angle brackets and values were in between each nodes. By comparison, JSON is composed of curly brackets which has a key and value. and the value can be defined by many types like integer, string, and array. To represent a array, it is presented by square brackets.

The following string below is an example for XML. I got it from MSDN:

XML
<?xml version="1.0" encoding="utf-8" ?>  
<bookstore xmlns="http://www.contoso.com/books">  
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">  
        <title>The Autobiography of Benjamin Franklin</title>  
        <author>  
            <first-name>Benjamin</first-name>  
            <last-name>Franklin</last-name>  
        </author>  
        <price>8.99</price>  
    </book>  
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">  
        <title>The Confidence Man</title>  
        <author>  
            <first-name>Herman</first-name>  
            <last-name>Melville</last-name>  
        </author>  
        <price>11.99</price>  
    </book>  
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">  
        <title>The Gorgias</title>  
        <author>  
            <name>Plato</name>  
        </author>  
        <price>9.99</price>  
    </book>  
</bookstore>  

The following one is an example for Json. I got this from this site.

JavaScript
{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Using the Code

I will upload my project though, I made two multiline textboxes which were having XML string, JSON string.

The first one named 'txtXmlSource', the other is 'txtJsonSource'.

Then, I need two textboxes for inputting some path, 'txtXPath' and 'txtJPath'. Those are used for your searches.

Then, when each job of finding value is finished, there will appear two textboxes, named 'txtXpathResult' and 'txtJPathresult'.

See this code below:

C#
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
using System.Windows.Forms;

using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace XmlJsonTest
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

        }

        private void btnXmlSearch_Click(object sender, EventArgs e)
        {
            try
            {
                using (StringReader readerPost = new StringReader(txtXmlSource.Text))
                {
                    XPathDocument xDoc = new XPathDocument(readerPost);
                    XPathNavigator xNav = xDoc.CreateNavigator();

                    #region empty namespace set
                    XmlNamespaceManager ns = new XmlNamespaceManager(xNav.NameTable);
                    var nodes = xNav.Select("//*");
                    while (nodes.MoveNext())
                    {
                        var nsis = nodes.Current.GetNamespacesInScope(XmlNamespaceScope.Local);
                        foreach (var nsi in nsis)
                        {
                            // to make a global namespace for non-named
                            var prf = (String.IsNullOrEmpty(nsi.Key)) ? "global" : nsi.Key;
                            if (String.IsNullOrEmpty(nsi.Value)) continue;

                            ns.AddNamespace(prf, nsi.Value);
                        }
                    }
                    #endregion

                    XPathExpression expression = xNav.Compile(txtXPath.Text);
                    expression.SetContext(ns);

                    XPathNavigator successNav = xNav.SelectSingleNode(expression);
                    if (successNav != null)
                    {
                        txtXPathResult.Text = successNav.Value;
                    }
                    else
                    {
                        txtXPathResult.Text = "";
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// install-package newtonsoft.json
        /// Installing 'Newtonsoft.Json 12.0.2'.
        /// Successfully installed 'Newtonsoft.Json 12.0.2'.
        /// Adding 'Newtonsoft.Json 12.0.2' to XmlJsonTest.
        /// Successfully added 'Newtonsoft.Json 12.0.2' to XmlJsonTest.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnJSonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                JObject jo = JObject.Parse(txtJSonSource.Text);

                IEnumerable<JToken> rst = jo.SelectTokens(txtJPath.Text);
                if (rst.Count() > 0)
                {
                    txtJPathResult.Text = rst.First().ToString();
                }
                else
                    txtJPathResult.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

//

As you may have known, you need to install 'Newtonsoft' for JSon. Use a 'Package Manage Console' (at your Visual Studio's top menu -> tool -> nuget package manager). The command to install is like this:

PM> Install-Package Newtonsoft.Json

History

  • 5/9/2019: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Wiseneosco
Korea (Republic of) Korea (Republic of)
You know I can't speak English well but I'm learning. If there anything wrong in my article. Understand me. Smile | :) I'm so thankful if you could correct this.
Anyway, I'm a software programmer in Korea. I have been doing development about 10 years.
I majored in Computer Science and Engineering. I'm using c# mainly. Bye!

Comments and Discussions

 
QuestionWhy not just have one menthod? Pin
tlford6511-May-19 16:22
professionaltlford6511-May-19 16:22 
AnswerRe: Why not just have one menthod? Pin
Bloody Chicken14-May-19 23:05
professionalBloody Chicken14-May-19 23:05 
GeneralRe: Why not just have one menthod? Pin
tlford6517-May-19 7:21
professionaltlford6517-May-19 7:21 
QuestionCompile in Visual Code? (not Visual Studio) Pin
Member 1225292710-May-19 14:17
Member 1225292710-May-19 14:17 
AnswerRe: Compile in Visual Code? (not Visual Studio) Pin
Bloody Chicken14-May-19 23:13
professionalBloody Chicken14-May-19 23:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.