C# xml reader, same element name - c#

I'm trying to read an element from my xml file.
I need to read an string in an "link" element inside the "metadata",
but there are 2 elements called "link", I only need the second one:
<metadata>
<name>visit-2015-02-18.gpx</name>
<desc>February 18, 2015. Corn</desc>
<author>
<name>text</name>
<link href="http://snow.traceup.com/me?id=397760"/>
</author>
<link href="http://snow.traceup.com/stats/u?uId=397760&vId=1196854"/>
<keywords>Trace, text</keywords>
I need to read this line:
<link href="http://snow.traceup.com/stats/u?uId=397760&vId=1196854"/>
This is the working code for the first "link" tag, it works fine,
public string GetID(string path)
{
string id = "";
XmlReader reader = XmlReader.Create(path);
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "link"))
{
if (reader.HasAttributes)
{
id = reader.GetAttribute("href");
MessageBox.Show(id + "= first id");
return id;
//id = reader.ReadElementContentAsString();
}
}
}
return id;
}
Does anyone know how I can skip the first "link" element?
or check if reader.ReadElementContentAsString() contains "Vid" or something like that?
I hope you can help me.

xpath is the answer :)
XmlReader reader = XmlReader.Create(path);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNodeList nodes = doc.SelectNodes("metadata/link");
foreach(XmlNode node in nodes)
Console.WriteLine(node.Attributes["href"].Value);

Use the String.Contains method to check if the string contains the desired substring, in this case vId:
public string GetID(string path)
{
XmlReader reader = XmlReader.Create(path);
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "link"))
{
if (reader.HasAttributes)
{
var id = reader.GetAttribute("href");
if (id.Contains(#"&vId"))
{
MessageBox.Show(id + "= correct id");
return id;
}
}
}
return String.Empty;
}
If acceptable you can also use LINQ2XML:
var reader = XDocument.Load(path); // or XDocument.Parse(path);
// take the outer link
Console.WriteLine(reader.Root.Element("link").Attribute("href").Value);
The output is always:
http://snow.traceup.com/stats/u?uId=397760&vId=1196854= first id
Another options is to use XPath like #user5507337 suggested.

XDocument example:
var xml = XDocument.Load(path); //assuming path points to file
var nodes = xml.Root.Elements("link");
foreach(var node in nodes)
{
var href = node.Attribute("href").Value;
}

Related

Reading specific data from XML file in C#

I want to read specific data from an XML file.
This is what I have come up with so far:
When I run my program without the (if (reader.Name == ControlID)) line reader.Value returns the right value,but when I include the if clause,it returns null
public void GetValue(string ControlID)
{
XmlTextReader reader = new System.Xml.XmlTextReader("D:\\k.xml");
string contents = "";
while (reader.Read())
{
reader.MoveToContent();
if (reader.Name == ControlID)
contents = reader.Value;
}
}
Go through following code:
XmlDocument doc = new XmlDocument();
doc.Load(filename);
string xpath = "/Path/.../config"
foreach (XmlElement elm in doc.SelectNodes(xpath))
{
Console.WriteLine(elm.GetAttribute("id"), elm.GetAttribute("desc"));
}
Using XPathDocument (faster, smaller memory footprint, read-only, weird API):
XPathDocument doc = new XPathDocument(filename);
string xpath = "/PathMasks/Mask[#desc='Mask_X1']/config"
XPathNodeIterator iter = doc.CreateNavigator().Select(xpath);
while (iter.MoveNext())
{
Console.WriteLine(iter.Current.GetAttribute("id"), iter.Current.GetAttribute("desc'));
}
Can also refer this link:
http://support.microsoft.com/kb/307548
This might be helpful to you.
You can try the following code for example xPath query:
XmlDocument doc = new XmlDocument();
doc.Load("k.xml");
XmlNode absoluteNode;
/*
*<?xml version="1.0" encoding="UTF-8"?>
<ParentNode>
<InfoNode>
<ChildNodeProperty>0</ChildNodeProperty>
<ChildNodeProperty>Zero</ChildNodeProperty>
</InfoNode>
<InfoNode>
<ChildNodeProperty>1</ChildNodeProperty>
<ChildNodeProperty>One</ChildNodeProperty>
</InfoNode>
</ParentNode>
*/
int parser = 0
string nodeQuery = "//InfoNode//ChildNodeProperty[text()=" + parser + "]";
absoluteNode = doc.DocumentElement.SelectSingleNode(nodeQuery).ParentNode;
//return value is "Zero" as string
var nodeValue = absoluteNode.ChildNodes[1].InnerText;

read only particular instance using xmlreader

I have a xml file that looks like
<Name>AAA</Name>
<Age>23</Age>
<I1>
<Element1>A</Element1>
<Element2>B</Element2>
<Element3>C</Element3>
<\I1>
<I2>
<Element1>AA</Element1>
<Element2>BB</Element2>
<Element3>CC</Element3>
</I2>
I am reading all the values of elements using xmlreader in C# 3.0. But now i have to change by reading only the values within particular start and end tage. For the xml file mentioned above, i need to read <Name>, <Age> by default and then i have a function that returns the value "I1" or "I2" which is basically the element names. If it returns "I1" then i should read only the elements between <I1> and </I1> and should not read <I2> and vice versa. So the code structure would be (just the logic please ignore the syntax errors) like
/******function that returns element name I1 or I2*********/
string elementName = func(a,b);
xmlreader reader = reader.create("test.xml");
while(reader.read())
{
switch(reader.nodetype)
{
case xmlnodetype.element:
string nodeName = reader.name
break;
case xmlnodetype.text
switch(nodeName)
{
/*************Read default name and age values*******/
case "Name":
string personName = reader.value
break;
case "Age":
string personAge = reader.value;
break;
/*******End of reading default values**************/
/*** read only elements between the value returned by function name above
If function returns I1 then i need to read only values between <I1> </I1> else read </I2> and </I2>**/
}
}
}
Thanks!
So assuming, since we dont have any other tags to go off, that your file would look something such as this from beginning to end
<?xml version="1.0" encoding="utf-8" ?>
<RootElement>
<UserInformation>
<Name>AAA</Name>
<Age>23</Age>
<I1>
<Element1>A</Element1>
<Element2>B</Element2>
<Element3>C</Element3>
<\I1>
<I2>
<Element1>AA</Element1>
<Element2>BB</Element2>
<Element3>CC</Element3>
</I2>
</UserInformation>
</RootElement>
and then to call it
System.IO.StreamReader sr = new System.IO.StreamReader("test.xml");
String xmlText = sr.ReadToEnd();
sr.Close();
List<UserInfo> finalList = readXMLDoc(xmlText);
if(finalList != null)
{
//do something
}
private List<UserInfo> readXMLDoc(String fileText)
{
//create a list of Strings to hold our user information
List<UserInfo> userList = new List<UserInfo>();
try
{
//create a XmlDocument Object
XmlDocument xDoc = new XmlDocument();
//load the text of the file into the XmlDocument Object
xDoc.LoadXml(fileText);
//Create a XmlNode object to hold the root node of the XmlDocument
XmlNode rootNode = null;
//get the root element in the xml document
for (int i = 0; i < xDoc.ChildNodes.Count; i++)
{
//check to see if we hit the root element
if (xDoc.ChildNodes[i].Name == "RootElement")
{
//assign the root node
rootNode = xDoc.ChildNodes[i];
break;
}
}
//Loop through each of the child nodes of the root node
for (int j = 0; j < rootNode.ChildNodes.Count; j++)
{
//check for the UserInformation tag
if (rootNode.ChildNodes[j].Name == "UserInformation")
{
//assign the item node
XmlNode userNode = rootNode.ChildNodes[j];
//create userInfo object to hold results
UserInfo userInfo = new UserInfo();
//loop through each if the user tag's elements
foreach (XmlNode subNode in userNode.ChildNodes)
{
//check for the name tag
if (subNode.Name == "Name")
{
userInfo._name = subNode.InnerText;
}
//check for the age tag
if (subNode.Name == "Age")
{
userInfo._age = subNode.InnerText;
}
String tagToLookFor = "CallTheMethodThatReturnsTheCorrectTag";
//check for the tag
if (subNode.Name == tagToLookFor)
{
foreach (XmlNode elementNode in subNode.ChildNodes)
{
//check for the element1 tag
if (elementNode.Name == "Element1")
{
userInfo._element1 = elementNode.InnerText;
}
//check for the element2 tag
if (elementNode.Name == "Element2")
{
userInfo._element2 = elementNode.InnerText;
}
//check for the element3 tag
if (elementNode.Name == "Element3")
{
userInfo._element3 = elementNode.InnerText;
}
}
}
}
//add the userInfo to the list
userList.Add(userInfo);
}
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
return null;
}
//return the list
return userList;
}
//struct to hold information
struct UserInfo
{
public String _name;
public String _age;
public String _element1;
public String _element2;
public String _element3;
}

How to update the XMLDocument using c#?

I want to update the xml document and i need to return the updated xml in string. I am trying like below. when i save the document it expects the file name. but i dont want to save this as file. i just want to get the updated xml in string.
string OldXml = #"<Root>
<Childs>
<first>this is first</first>
<second>this is second </second>
</Childs
</Root>";
XmlDocument NewXml = new XmlDocument();
NewXml.LoadXml(OldXml );
XmlNode root = NewXml.DocumentElement;
XmlNodeList allnodes = root.SelectNodes("*");
foreach (XmlNode eachnode in allnodes)
{
if (eachnode.Name == "first")
{
eachnode.InnerText = "1";
}
}
NewXml.Save();
string newxml = NewXml.OuterXml;
You don't need to call Save method because string is immutable, your problem is in root.SelectNodes("*"), it just get child nodes, not all level of nodes. You need to go one more level:
foreach (XmlNode eachnode in allnodes)
{
var firstNode = eachnode.ChildNodes.Cast<XmlNode>()
.SingleOrDefault(node => node.Name == "first");
if (firstNode != null)
{
firstNode.InnerText = "1";
}
}
string newxml = NewXml.OuterXml;
It would be strongly recommended using LINQ to XML, it's simpler:
var xDoc = XDocument.Parse(OldXml);
foreach (var element in xDoc.Descendants("first"))
element.SetValue(1);
string newXml = xDoc.ToString();
Your iteration never reaches a node called "first". Else it would work fine without saving the NewXml.
You could however use a XElement and iterate over all descendants.
string OldXml = #"<Root>
<Childs>
<first>this is first</first>
<second>this is second </second>
</Childs>
</Root>";
var NewXml = XElement.Parse(OldXml);
foreach (var node in NewXml.Descendants())
{
if (node.Name.LocalName == "first")
{
node.Value = "1";
}
}
var reader = NewXml.CreateReader();
reader.MoveToContent();
string newxml = reader.ReadInnerXml();

C# : Getting all nodes of XML doc

Is there a simple way, to get all nodes from an xml document? I need every single node, childnode and so on, to check if they have certain attributes.
Or will I have to crawl through the document, asking for childnodes?
In LINQ to XML it's extremely easy:
XDocument doc = XDocument.Load("test.xml"); // Or whatever
var allElements = doc.Descendants();
So to find all elements with a particular attribute, for example:
var matchingElements = doc.Descendants()
.Where(x => x.Attribute("foo") != null);
That's assuming you wanted all elements. If you want all nodes (including text nodes etc, but not including attributes as separate nodes) you'd use DescendantNodes() instead.
EDIT: Namespaces in LINQ to XML are nice. You'd use:
var matchingElements = doc.Descendants()
.Where(x => x.Attribute(XNamespace.Xmlns + "aml") != null);
or for a different namespace:
XNamespace ns = "http://some.namespace.uri";
var matchingElements = doc.Descendants()
                    .Where(x => x.Attribute(ns + "foo") != null);
see here: Iterating through all nodes in XML file
shortly:
string xml = #"
<parent>
<child>
<nested />
</child>
<child>
<other>
</other>
</child>
</parent>
";
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
Console.WriteLine(rdr.LocalName);
}
}
In my opinion the simplest solution is using XPath. Also this works if you have .NET 2:
var testDoc = new XmlDocument();
testDoc.LoadXml(str);
var tmp = testDoc.SelectNodes("//*"); // match every element
XDocument.Descendants will return you all the nodes in a flat enumerable.
Check out LINQ to XML. That does what you need.
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx
You can use the SelectMany extension for example.
But if you want to check the values you can just use LINQ to create where-statements.
public void AddWithChildren(XmlNode xnod, Int32 intLevel) //,XmlDocument xmlDoc
{
List<IEnumerable> item = new List<IEnumerable>();
XmlNode xnodWorking;
String strIndent = new string('-', 2 * intLevel);
String strIndent1 = new string('#', 2 * intLevel);
if (xnod.NodeType == XmlNodeType.Element)
{
item.Add(new ListXML(strIndent + xnod.Name, strIndent + xnod.Name, ""));
XmlNamedNodeMap mapAttributes = xnod.Attributes;
foreach (XmlNode xnodAttribute in mapAttributes)
{
item.Add(new ListXML(strIndent1 + xnodAttribute.Name, strIndent1 + xnodAttribute.Name, ""));
}
if (xnod.HasChildNodes)
{
xnodWorking = xnod.FirstChild;
while (xnodWorking != null)
{
AddWithChildren(xnodWorking, intLevel + 1);
xnodWorking = xnodWorking.NextSibling;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument document = new XmlDocument();
string xmlStr;
using (var wc = new WebClient())
{
xmlStr = wc.DownloadString("test.xml");
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);
XmlNode xnod = xmlDoc.DocumentElement;
AddWithChildren(xnod, 1);
}
string AttrNameerr = "err";//find error code in xml
XmlReader rdr = XmlReader.Create(new stem.IO.StringReader(somesXMLtring));//somesXMLtring is xml in string variable we want to find attribute in.
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
//Found the new element, now check if the required attribute is present or not. if not, ignore, if yes then display the same
string val = rdr.GetAttribute(AttrNameerr);//AttrNameerr is name of attribute we need to get value of which. here we are searching for error code stored as value of 'err' attribute
if (val != null)
textBox.Text = strResult = "error = " + rdr.GetAttribute(AttrNameerr);
}
}

Check if XML Element exists

How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.
if(doc.SelectSingleNode("//mynode")==null)....
Should do it (where doc is your XmlDocument object, obviously)
Alternatively you could use an XSD and validate against that
You can iterate through each and every node and see if a node exists.
doc.Load(xmlPath);
XmlNodeList node = doc.SelectNodes("//Nodes/Node");
foreach (XmlNode chNode in node)
{
try{
if (chNode["innerNode"]==null)
return true; //node exists
//if ... check for any other nodes you need to
}catch(Exception e){return false; //some node doesn't exists.}
}
You iterate through every Node elements under Nodes (say this is root) and check to see if node named 'innerNode' (add others if you need) exists. try..catch is because I suspect this will throw popular 'object reference not set' error if the node does not exist.
//if the problem is "just" to verify that the element exist in the xml-file before you
//extract the value you could do like this
XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName("YOUR_ELEMENTNAME");
if (YOURTEMPVARIABLE.Count > 0 )
{
doctype = YOURTEMPVARIABLE[0].InnerXml;
}
else
{
doctype = "";
}
Not sure what you're wanting to do but using a DTD or schema might be all you need to validate the xml.
Otherwise, if you want to find an element you could use an xpath query to search for a particular element.
How about trying this:
using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
//do your code here
}
}
}
additionally to sangam code
if (chNode["innerNode"]["innermostNode"]==null)
return true; //node *parentNode*/innerNode/innermostNode exists
You can validate that and much more by using an XML schema language, like XSD.
If you mean conditionally, within code, then XPath is worth a look as well.
Following is a simple function to check if a particular node is present or not in the xml file.
public boolean envParamExists(String xmlFilePath, String paramName){
try{
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(xmlFilePath));
doc.getDocumentElement().normalize();
if(doc.getElementsByTagName(paramName).getLength()>0)
return true;
else
return false;
}catch (Exception e) {
//error handling
}
return false;
}
A little bit late, but if it helps, this works for me...
XmlNodeList NodoEstudios = DocumentoXML.SelectNodes("//ALUMNOS/ALUMNO[#id=\"" + Id + "\"]/estudios");
string Proyecto = "";
foreach(XmlElement ElementoProyecto in NodoEstudios)
{
XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName("proyecto");
Proyecto = (EleProyecto[0] == null)?"": EleProyecto[0].InnerText;
}
//Check xml element value if exists using XmlReader
using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING")))
{
if (xmlReader.ReadToFollowing("XMLNODE"))
{
string nodeValue = xmlReader.ReadElementString("XMLNODE");
}
}
Just came across the same problem and the null-coalescing operator with SelectSingleNode worked a treat, assigning null with string.Empty
foreach (XmlNode txElement in txElements)
{
var txStatus = txElement.SelectSingleNode(".//ns:TxSts", nsmgr).InnerText ?? string.Empty;
var endToEndId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
var paymentAmount = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).InnerText ?? string.Empty;
var paymentAmountCcy = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).Attributes["Ccy"].Value ?? string.Empty;
var clientId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
var bankSortCode = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
//TODO finish Object creation and Upsert DB
}
string name = "some node name";
var xDoc = XDocument.Load("yourFile");
var docRoot = xDoc.Element("your docs root name");
var aNode = docRoot.Elements().Where(x => x.Name == name).FirstOrDefault();
if (aNode == null)
{
return $"file has no {name}";
}
//I am finding childnode ERNO at 2nd but last place
If StrComp(xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).Name.ToString(), "ERNO", CompareMethod.Text) = 0 Then
xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).InnerText = c
Else
elem = xmldoc.CreateElement("ERNo")
elem.InnerText = c.ToString
root.ChildNodes(i).AppendChild(elem)
End If

Categories

Resources