I have a string in which I need to extract all of the FieldRef names from the ViewField section of the string. They need to be input into an array. Been struggling with this for a while since im new to c#. Thanks.
<View>
<Query>
<OrderBy>
<FieldRef Name="ID" />
</OrderBy>
</Query>
<ViewFields>
<FieldRef Name="LinkTitle" />
<FieldRef Name="User" />
<FieldRef Name="Permissions" />
</ViewFields>
<RowLimit Paged="TRUE">30</RowLimit>
<JSLink>clienttemplates.js</JSLink>
<XslLink Default="TRUE">main.xsl</XslLink>
<Toolbar Type="Standard"/>
</View>
This returns only FieldRefs from ViewFields:
var doc = XDocument.Parse(xmlString);
var results = doc.Root.Element("ViewFields").Elements("FieldRef")
.Select(e => e.Attribute("Name").Value);
You can use XDocument to load the string as xml and then use Linq to get the values.
var doc = XDocument.Parse(str);
var res = doc
.Descendants("ViewFields")
.Descendants("FieldRef")
.Select(x => x.Attribute("Name").Value);
Load method is trying to load xml from a file and LoadXml from a string
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string xpath = "View/Query/ViewFields";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
var arr = childrenNode.SelectSingleNode("//FieldRef").Value;
}
Related
I have a section of XML that I am trying to pull out a name from.
the XML looks like this:
here is the xml layout.
<point href="/software/point/av/371/">
<obj is="testdata/">
<bool val="true" name="eventDetectionEnable" />
<real val="-500.6300048828125" name="minimumValue" />
<int val="0" name="controlClass" />
<int val="1490" name="revision" />
<real val="0" name="highLimit" />
<int val="6" name="dimensionality" />
<reltime val="PT0S" name="heartbeatInterval" />
<enum val="event" name="notifyType" />
<str val="Verticle Spread Pressure" name="name" />
<real val="0" name="deadband" />
<real val="0" name="lowLimit" />
<str val="" name="protocolID" />
<str val="" name="description" />
<reltime val="PT0S" name="eventTimeDelay" />
<real val="1" name="covIncrement" />
<real val="7.9999995231628418" name="relinquishDefault" />
<op name="notifyNow" />
<real val="500.6300048828125" name="maximumValue" />
</obj>
</point>
I need to pull out the name from line
<str val="Verticle Spread Pressure" name="name" />
I can get a list of all the nodes and read the href tag, but nothing below
var data = OpenPLCfile(ofd.FileName, "pointconfig.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(data);
string xpath = "PointsConfiguration/SoftwarePoints/point";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
string pointID = childrenNode.Attributes["href"].Value;
Console.WriteLine(pointID)
}
You can apply an XPath expression on the XmlNode via the SelectSingleNode method.
XmlNode nameNode = childrenNode.SelectSingleNode("obj/str[#name='name']/#val");
string name = nameNode.Value;
Full example
var data = OpenPLCfile(ofd.FileName, "pointconfig.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(data);
string xpath = "PointsConfiguration/SoftwarePoints/point";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
string pointID = childrenNode.Attributes["href"].Value;
Console.WriteLine(pointID)
XmlNode nameNode = childrenNode.SelectSingleNode("obj/str[#name='name']/#val");
string name = nameNode.Value;
Console.WriteLine(name);
}
If you only want to get the value of name attribute from the element str where value of val attribute is "Verticle Spread Pressure", then here is the solution:
var data = OpenPLCfile(ofd.FileName, "pointconfig.xml");
XDocument doc = XDocument.Parse(data);
var strElements = doc.Descendants("str");
var targetElement = strElements.Where(x => x.Attribute("val") != null && x.Attribute("val").Value == "Verticle Spread Pressure").FirstOrDefault();
if (targetElement != null)
{
string name = targetElement.Attribute("name").Value;
}
System.Xml.Linq is the namespace for XDocument
Using Xml Linq you can get a dictionary of all named items
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> dict = doc.Descendants("obj").FirstOrDefault().Elements()
.GroupBy(x => (string)x.Attribute("name"), y => (string)y.Attribute("val"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}
Is there a way we can sort xmlnodes based on attribute values? The point is that every child node has a different name, despite it, I want to sort them by attribute.
E.g.
<Doc>
<mar_03 data="03">
<Mattina_Turno_1 />
</mar_03>
<dom_01 data="01">
<Mattina_Turno_1 />
</dom_01>
<mer_04 data="04">
<Mattina_Turno_1 />
<Mattina_Turno_2 />
</mer_04>
</Doc>
Should become
<Doc>
<dom_01 data="01">
<Mattina_Turno_1 />
</dom_01>
<mar_03 data="03">
<Mattina_Turno_1 />
</mar_03>
<mer_04 data="04">
<Mattina_Turno_1 />
<Mattina_Turno_2 />
</mer_04> </Doc>
How can I do it? After sorting obviously I want to overwrite the file.
This answer does not fix my problem since i can not define the node "item" since every my nodes are named differently.
Thanks, and please do not mark it as duplicate, because it is not!
Please try,
XDocument xdoc = XDocument.Load("File.xml");
var result = xdoc.Element("Doc")
.Elements()
.OrderBy(s => (int)s.Attribute("data"));
string xmlOutPut = string.Empty;
result.ToList().ForEach(a =>
{
xmlOutPut += a;
});
Where data and Doc is the parent element is your attribute according to your example. File.xml is your xml file name. You will get the sorted output in 'xmlOutPut'
or everything in a single Linq query,
XDocument xdoc = XDocument.Load("XMLFile2.xml");
string xmlOutPut = string.Empty;
xdoc.Element("Doc")
.Elements()
.OrderBy(s => (int)s.Attribute("data"))
.ToList().ForEach(a =>
{
xmlOutPut += a;
});
Sorting
XDocument xDoc = XDocument.Load("FileName.xml");
var res = xDoc.Element("Doc")
.Elements()
.OrderByDescending(c => (int) c.Attribute("data"));
Then to save it:
XDocument doc = new XDocument(new XElement("Doc", res));
doc.Save("FileName.xml");
I have an XML in this Format and I want to get List of Line ID and its Name
<ArrayOfLines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<LineStatus ID="0" StatusDetails="">
<BranchDisruptions />
<Line ID="1" Name="Line1" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
<LineStatus ID="1" StatusDetails="">
<BranchDisruptions />
<Line ID="2" Name="Line2" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
</ArrayOfLines>
and This is the code I have written:
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = from c in xmlFile.Descendants("LineStatus") select c;
but it is not returning me any results.
Here is my idea but you have to create list "namesList" and "idList" before. Try this:
XDocument xDoc = XDocument.Load("your xml file");
foreach (var elem in xDoc.Document.Descendants("line"))
{
idList.Add(elem.Attribute("ID").Value);
namesList.Add(elem.Attribute("Name").Value);
}
And you have full controll by index of each list to this data. After that you can also create object of these 2 elements
You have an xml namespace, you need to specify it with element names:
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var query = from c in xmlFile.Descendants(ns + "LineStatus") select c;
Try this...
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = (from c in xmlFile.Descendants("Line")
select new {
ID=c.Attribute("ID").Value,
Name=c.Attribute("Name").Value
}).ToList();;
My questions is regarding XML to LINQ where i have something as following structure:
<Or>
<value />
<Or>
<value />
<Or> //this is the deepest "or" element i should get in this case
<value />
<value />
</Or>
</Or>
</Or>
Which i basically build programmatically through the recrusion, but my questions i rather how to get the deepest Or element?
If i do:
elements.Element("Or"), it just gets me the first top element Or ....
Waitin for response.
XDocument xDoc = XDocument.Parse(xml); //XDocument.Parse(filename);
var deepestOr = xDoc.Descendants("Or")
.First(or => !or.Descendants("Or").Any());
Try that
var bench = XElement.Parse(#"<Or><value /><Or><value /><Or><value /><value /></Or></Or></Or>");
var lastOne = bench.Descendants("Or").Where( n => n.NodeType == XmlNodeType.Element).Last();
Result:
<Or>
<value />
<value />
</Or>
No matter how deep it is
This will give you the result:
XDocument doc = XDocument.Parse(#"<Or><value /><Or><value /><Or><value /><value /></Or></Or></Or>");
// take 'Or' node which contains no 'Of' nodes
var deepest = doc.Descendants("Or").Where(node => node.Descendants("Or").Count() == 0);
I am using Imgur api to upload image from my webapp. How to extract the URL from tag of this XML string using C# Asp.net
<upload>
<image>
<name />
<title />
<caption />
<hash>MkUDH</hash>
<deletehash>kP5lIWWU0vDqrO1</deletehash>
<datetime>2012-02-28 11:47:25</datetime>
<type>image/jpeg</type>
<animated>false</animated>
<width>640</width>
<height>480</height>
<size>173578</size>
<views>0</views>
<bandwidth>0</bandwidth>
</image>
<links>
<original>http://i.imgur.com/MkUDH.jpg</original>
<imgur_page>http://imgur.com/MkUDH</imgur_page>
<delete_page>http://imgur.com/delete/kP5lIWWU0vDqrO1</delete_page>
<small_square>http://i.imgur.com/MkUDHs.jpg</small_square>
<large_thumbnail>http://i.imgur.com/MkUDHl.jpg</large_thumbnail>
</links>
</upload>
You may try Linq Xml to read xml document and extract element value.
XDocument doc = XDocument.Load(file);
var result = doc.Root.Element("links").Element("original").Value;
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // your XML String
XmlNodeList xnList = xml.SelectNodes("/upload/links");
foreach (XmlNode xn in xnList)
{
string original= xn["original"].InnerText;
string imgur_page = xn["imgur_page"].InnerText;
string delete_page = xn["delete_page"].InnerText;
string small_square = xn["small_square"].InnerText;
string large_thumbnail= xn["large_thumbnail"].InnerText;
}
var url = Regex.Replace(s, #".*original\>(.*)\<\/original\>.*", "$1")
Output:
http://i.imgur.com/MkUDH.jpg