How to get attribute xml without loop c# - c#

i have xml file like this
> <?xml version='1.0' ?>
<config>
<app>
<app version="1.1.0" />
> </app>
</config>
and i want to read attribute version from node app
without any loop like this
while(reader.read()) or foreach etc.
Thanks

XmlDocument document = new XmlDocument();
document.Load("D:/source.xml");
XmlNode appVersion1 = document.SelectSingleNode("//app[#version]/#version");
XmlNode appVersion2 = document["config"]["app"]["app"].Attributes["version"];
Console.WriteLine("{0}, {1}",
appVersion1.Value,
appVersion2.Value);

You can do it this way.
XmlDocument doc = new XmlDocument();
string str = "<config><app><app version=" + "\"1.1.0\"" + "/></app></config>";
doc.LoadXml(str);
var nodes = doc.GetElementsByTagName("app");
foreach (XmlNode node in nodes)
{
if (node.Attributes["version"] != null)
{
string version = node.Attributes["version"].Value;
}
}
And you need to this for loop cause you got two nodes with same name App.
If you have a single node with name App,
XmlDocument doc = new XmlDocument();
string str = "<config><app version=" + "\"1.1.0\"" + "/></config>";
doc.LoadXml(str);
var node = doc.SelectSingleNode("//app");
if (node.Attributes["version"] != null)
{
string version = node.Attributes["version"].Value;
Console.WriteLine(version);
}

You can use linq to do
string stringXml= "yourXml Here";
XElement xdoc = XElement.Parse(stringXml);
var result= xdoc.Descendants("app").FirstOrDefault(x=> x.Attribute("version") != null).attribute("version").Value;
or:
var result = xdoc.Descendants("app").Where(x => x.Attribute("version") != null)
.Select(x => new { Version = x.Value });

Related

Can't get attribute value with C# XPath

I've spent so much time with this already, still can't get the value of NTE attribute. Can someone please help?
C#
StreamReader sr = new StreamReader(resp.GetResponseStream());
XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
XPathNodeIterator node = xmlNav.Select("/DATA2SC/CALL");
string dne = xmlNav.GetAttribute("NTE", "");
Console.WriteLine(dne);
sr.Close();
XML
<?xml version="1.0"?>
<DATA2SC PIN="00000">
<CALL
TR_NUM="00000001"
STATUS="WAITING_FOR_APPROVAL"
NTE="$15.00">
<PROBLEM>
Text
</PROBLEM>
</CALL>
</DATA2SC>
Can you try this code please ?
I already check and it's work
StreamReader sr = new StreamReader("c:\\x.xml");
XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
string dne = node.GetAttribute("NTE", "");
Console.WriteLine(dne);
OR
XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
foreach (var node1 in docXmlWorld.Descendants("DATA2SC"))
{
foreach (var node2 in node1.Descendants("CALL"))
{
string dne = node2.Attribute("NTE").Value;
Console.Out.WriteLine(dne);
}
}
Or you can do like this too:
XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
//Get the first child => [DATA2SC]
XElement elementNodeDATA2SC = docXmlWorld.Element("DATA2SC");
//Get the first child => [CALL]
XElement elementNodeCALL = elementNodeDATA2SC.Element("CALL");
//Get the attribute NTE from [CALL] node
string dne = elementNodeCALL.Attribute("NTE").Value;
Console.Out.WriteLine(dne);
The Select method, returns a collection of all nodes with the specified XPath.
You can use SelectSingleNode, to select the first node.
var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
string dne = node.GetAttribute("NTE", "");

how to get the value from innerXMl correctly

I plan to retrieve each suggestion in array and then stroe it in to the list. I have trouble retrieve the option node data, in this pattern {aeroplane,aeroplanes, aerobian} {i}, Any kind soul can help me out with it.
XmlDocument findStringDoc = new XmlDocument();
findStringDoc.Load (Application.dataPath+ "/" + filename);
XmlNodeList nodeList = findStringDoc.SelectNodes("/results/error");
//XmlNodeList suggestionNodeList = findStringDoc.SelectNodes("/results/error/suggestions/option");
foreach(XmlNode xn in nodeList){
errorString.Add(xn["string"].InnerText);
errorType.Add(xn["type"].InnerText);
//string temp = xn["suggestion"].InnerXml;
////TODO: Retrieve suggestions here!
XmlNodeList suggestionNodeList = findStringDoc.SelectNodes("/suggestions");
foreach(XmlNode yn in suggestionNodeList){
option[suggestionNodeList.Count] = yn["option"].InnerText;
Debug.Log(yn["option"].InnerText);
}
suggestionResult.Add (option);
//Debug.Log(suggestionResult);
//XmlNodeList suggestionNodeList = findStringDoc.SelectNodes("/results/error[string='{0}']/suggestions/option",errorString[i]);
}
<results>
<error>
<string>aeroplan</string>
<description>Spelling</description>
<precontext>a</precontext>
<suggestions>
<option>aeroplane</option>
<option>aeroplanes</option>
<option>aerobian</option>
</suggestions>
<type>spelling</type>
</error>
<error>
<string>i</string>
<description>Make I uppercase</description>
<precontext></precontext>
<suggestions>
<option>I</option>
</suggestions>
<type>grammar</type>
<url>http://service.afterthedeadline.com/info.slp?text=i&tags=PRP&engine=1</url>
</error>
</results>
You can use my code below:
private static void GetSuggestionOption(string filename, string value, string optionSuggest)
{
XDocument xDoc = XDocument.Parse(filename);
var parentNode = xDoc.Descendants().Where(x => x.Value == value).Ancestors().FirstOrDefault();
var childNode = parentNode.Descendants().Where(x => x.Name == optionSuggest);
childNode.ToList().ForEach(x => Console.WriteLine(x.Value));
}
Calling: GetSuggestionOption(fileName, "aeroplan", "option");
Happy Coding!
You can use XmlDocument.SelectNodes() method passing suitable XPath string parameter to select specific element(s) from XmlDocument, for example :
public void GetSuggestionOption(string keyword)
{
XmlDocument doc = new XmlDocument();
doc.Load (Application.dataPath+ "/" + filename);
string xpath = string.Format("//error[string='{0}']/suggestions/option", keyword);
XmlNodeList optionSuggestionList = doc.SelectNodes(xpath);
foreach (XmlNode option in optionSuggestionList)
{
Debug.Log(option.InnerXml);
}
}
You can call the method this way for example : GetSuggestionOption("aeroplan")

C# : Modify a xml node

i have that xml file :
<?xml version="1.0" encoding="utf-8"?>
<reminders>
<reminder>
<Title>Alarm1</Title>
<Description>Desc1</Description>
<Time>03/07/2012 10:11AM</Time>
<snooze>1</snooze>
<repeat>None</repeat>
</reminder>
</reminders>
And i want to modify the innertext from Alarm1 to another value so i wrote that code which actually duplicate the entire node .
XmlDocument xml = new XmlDocument();
xml.Load("0.xml");
XmlNodeList elements = xml.SelectNodes("//reminders");
foreach (XmlNode element in elements)
{
if (element.InnerText == "Alarm1")
{
XmlNode newvalue = xml.CreateElement("MODIFIED");
element.ReplaceChild(newvalue, element);
xml.Save("0.xml");
}
}
And then tried another code :
foreach (XmlElement element in xml.SelectNodes("//reminder"))
{
if (element.InnerText == "Alarm1")
{
XmlNode newvalue = xml.CreateElement("MODIFIED");
element.ReplaceChild(newvalue, element);
xml.Save("0.xml");
}
}
But also doesn`t work....
EDIT 1 : [Figured out a new code]
XmlDocument xml = new XmlDocument();
xml.Load("0.xml");
foreach (XmlElement element in xml.SelectNodes("//reminder"))
{
foreach (XmlElement element1 in element)
{
if (element.SelectSingleNode("//Title").InnerText == "Alarm1")
{
XmlNode newvalue = xml.CreateElement("MODIFIED");
element.ReplaceChild(newvalue, element1);
xml.Save("0.xml");
}
}
}
But it made the Alarm1 becomes
<MODIFIED />
EDIT 2 : [I SOLVED IT :D]
Okay here is the code i could figure out :
XmlDocument xml = new XmlDocument();
xml.Load("0.xml");
foreach (XmlElement element in xml.SelectNodes("//reminder"))
{
foreach (XmlElement element1 in element)
{
if (element.SelectSingleNode("//Title").InnerText == "Alarm1")
{
MessageBox.Show(element1.InnerText);
XmlNode newvalue = xml.CreateElement("Title");
newvalue.InnerText = "MODIFIED";
element.ReplaceChild(newvalue, element1);
xml.Save("0.xml");
}
}
}
I`ll really appreciate your helps and thanks.
Try this:
xml.SelectSingleNode("//reminder/Title").InnerText = "NewValue";
Your foreach line is simply looping through a list of elements called "reminders", not it's child nodes.
Take a look at this xpath tutorial for more information:
http://www.w3schools.com/xpath/xpath_intro.asp
If you want to use linq with xml (I find it the best way) then you will want to use the System.Xml.Linq namespace. The classes in that namespace are all prefixed with just X not Xml. The functionality in this namespace is newer, better and much easier to manipulate with Linq.
var xml = XDocument.Load("0.xml");
var alarm1 = xml.Descendants("reminder")
.Single(r => r.Element("Title") == "Alarm1");
This code will give you a variable, alarm1 that is the reminder that has a title node of "Alarm1."
From that point its not clear to me exactly what you want to modify. If you just want to change the title then ...
alarm1.Element("Title").Value = "MODIFIED";
xml.Save("0.xml");
XDocument doc = XDocument.Load("0.xml");
IEnumerable<XElement> rech =
from el in doc.Root.Elements("reminder")
where (string)el.Element("Title") == "Alarm1"
select el;
if (rech.Count() != 0)
{
foreach (XElement el in rech)
{
el.Element("Title").SetValue("NEW TITLE");
}
}
doc.Save("0.xml");
XDocument xDoc = XDocument.Load(.....);
xDoc.Descendants("Title").First().Value = "New Value";
xDoc.Save(...)
XmlDocument xml = new XmlDocument();
xml.Load(...);
var newTitle = "MODIFIED";
var title_node = xml.GetElementsByTagName("Title");
if(!string.IsNullOrEmpty(newTitle) && title_node.Count > 0)
{
title_node[0].InnerText = newTitle;
}

Reading XML using C#

<Tasks>
<AuxFiles>
<FileType AttachmentType='csv' FileFormat ='*.csv'>
</AuxFiles>
</Tasks>
What is the syntax in C# to get the FileFormat if I know the AttachmentType?
Any and all help is always appreciated.
I'd use LINQ to XML:
var doc = XDocument.Load("file.xml");
var format = doc.Descendants("FileType")
.Where(x => (string) x.Attribute("AttachmentType") == type)
.Select(x => (string) x.Attribute("FileFormat"))
.FirstOrDefault();
This will give null if there is no matching element or if the first FileType with a matching AttachmentType doesn't have a FileFormat attribute.
You can use XElement and the query support for that.
XElement element = XElement.Parse(#"<Tasks>
<AuxFiles>
<FileType AttachmentType='csv' FileFormat ='*.csv' />
</AuxFiles>
</Tasks>");
string format = element.Descendants("FileType")
.Where(x => x.Attribute("AttachmentType").Value == "csv")
.Select(x => x.Attribute("FileFormat").Value)
.First();
Console.WriteLine(format);
Try this code:
string fileFormat = string.Empty;
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fileName);
XmlNodeList auxFilesList = xDoc.GetElementsByTagName("AuxFiles");
for (int i = 0; i < auxFilesList.Count; i++)
{
XmlNode item = classList.Item(i);
if (item.Attributes["AttachmentType"].Value == "csv")
{
fileFormat = item.Attributes["FileFormat"].Value;
}
}
You can use XPATH to query any element in your XML file.
see this ULR: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
check also this SO post: "How to query a peer XMLNode .NET"
Another way of doing it is:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("path\\to\\file.xml");
// Select the node where AttachmentType='csv'
XmlNode node = xDoc.SelectSingleNode("/Tasks/AuxFiles/FileType[#AttachmentType='csv']");
// Read the value of the Attribute 'FileFormat'
var fileFormat = node.Attributes["FileFormat"].Value;

How to set attribute to an XML element using linq to xml in C#

i've an xml file like
<Root>
<Steps>
<Step Test="SampleTestOne" Status="Fail" />
<Step Test="SampleTestTwo" Status="Fail" />
</Steps>
</Root>
i need to change or overwrite the attribute value of "Status" in the Step element.
Now i'm using XmlDocument for this
like
XmlDocument XDoc = new XmlDocument();
XDoc.Load(Application.StartupPath + "\\Sample.xml");
XmlNodeList NodeList = XDoc.SelectNodes("//Steps/Step");
foreach (XmlNode Node in NodeList)
{
XmlElement Elem = (XmlElement)Node;
String sTemp = Elem.GetAttribute("Test");
if (sTemp == "SampleTestOne")
Elem.SetAttribute("Status", "Pass");
}
I need search the element and to update the status
is there any way to do this using XDocumentin c#
Thanks in advance
string filename = #"C:\Temp\demo.xml";
XDocument document = XDocument.Load(filename);
var stepOnes = document.Descendants("Step").Where(e => e.Attribute("Test").Value == "SampleTestOne");
foreach (XElement element in stepOnes)
{
if (element.Attribute("Status") != null)
element.Attribute("Status").Value = "Pass";
else
element.Add(new XAttribute("Status", "Pass"));
}
document.Save(filename);
You can use this code:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Steps/Step");
node.Attributes["Status"].Value = "True";
xmlDoc.Save(xmlFile);

Categories