What is the JSON.NET equivalent of XML's XPath, SelectNodes, SelectSingleNode?
Json.NET has SelectToken. It uses a syntax similar to DataBinder.Eval to get JSON via a string expression:
JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");
// get name token of first person and convert to a string
string name = (string)o.SelectToken("People[0].Name");
Or if you wanted to select multiple values:
JObject o = JObject.Parse("{'People':[{'Name':'Jeff','Roles':['Manager', 'Admin']}]}");
// get role array token of first person and convert to a list of strings
IList<string> names = (string)o.SelectToken("People[0].Roles").Select(t => (string)t).ToList();
Documentation: Querying JSON with SelectToken
Parsing Json string using Json.NET
See: What is the JSON.NET equivalent of XML's XPath, SelectNodes, SelectSingleNode?
var data = GetJson();
//You can use the SelectToken to get the value similar to XPath.
var value = JArray.Parse(data)
.SelectToken("[0][0].metadata.county_name")
.Value<string>();
This can be extended to support multiple elements:
var jArray = JArray.Parse(data);
var countyNames = new List<string>();
foreach(var element in jArray.SelectToken("[0]"))
{
var value = element.SelectToken("metadata.county_name").Value<string>();
countyNames.Add(value);
}
Json.net: Can JObject.SelectToken do the same thing the XPath can do? If yes what are the syntax?
From author of JSON.NET:
Since Json.NET 6.0 supes up SelectToken with full support for JSONPath, an XPath like querying language for JSON.
JObject o = JObject.Parse(@"{
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
// manufacturer with the name 'Acme Co'
var acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");
More details on blog post
What version of XPath does XmlDocument.SelectSingleNode use?
Microsoft never implemented XPath 2.0 or Xslt 2.0... See for example this uservoice (aptly named Native support for XPath 2.0 or XSLT 2.0 in .NET) of 2013...
Last comment of March 2015 by one user:
i guess we will never see this as the world doesn't like XML anymore, it's all about JSON. Which is a shame as XML is still far better for a number of key scenarios than JSON.
SelectSingleNode, how to write xpath query using string variable?
If you are looking for child nodes "*"
would likely work. Or simply get all child nodes via XmlNode.ChildNodes
and grab Value
or InnerText
.
SelectSingleNode in XML for select second element doesn't work in C#
You're using //
at the start of each of your selections - which means "find descendant nodes starting at the root" (so the context is irrelevant). You could either do things in one step as per Jeffrey's answer, or use relative paths:
doc.SelectSingleNode("config")
.SelectSingleNode("SecondNode")
.SelectSingleNode("ShowBlahBlah")
Personally I'd use LINQ to XML instead, if at all possible:
var doc = XDocument.Parse(sReadXml);
var changes = doc.Root.Element("SecondNode").Element("ShowBlahBlah");
LINQ to XML is generally a much cleaner API than XmlDocument
et al.
Related Topics
Windows 7 and Vista Uac - Programmatically Requesting Elevation in C#
Sqlbulkcopy Insert with Identity Column
Attach Debugger in C# to Another Process
I Didn't Find "Zipfile" Class in the "System.Io.Compression" Namespace
Inconsistency in Divide-By-Zero Behavior Between Different Value Types
No Templates in Visual Studio 2017
SQL Where Clause Matching Values with Trailing Spaces
Open Default Mail Client Along with a Attachment
What Is the "Right" Way to Bring a Windows Forms Application to the Foreground
Use Reflection to Invoke an Overridden Base Method
Ef Linq Error After Change from Dotnet Core 2.2.6 to 3.0.0
Is It Ok to Use a String as a Lock Object
Why Use Async/Await All the Way Down
How to List the Contents of a .Zip Folder in C#
What's the Difference Between Application.Run() and Form.Showdialog()