This question already has answers here:
Check if XML Element exists
(13 answers)
C# Linq to XML check if element exists
(3 answers)
Closed 5 years ago.
I am trying to check if node "DEF" exists in my xml file
My xml file looks like this:
<Struct>
<A>
<ABC>
</ABC>
<DEF>
</DEF>
</A>
<B>
<GHI>
</GHI>
</B>
</Struct>
And my code looks like this:
XmlDocument stru = new XmlDocument();
stru.Load(path + "Structure.xml");
if (stru.ChildNodes[0].HasChildNodes)
{
for (int i = 0; i < stru.ChildNodes[0].ChildNodes.Count; i++)
{
if (stru.ChildNodes[0].ChildNodes[i].Attributes["DEF"] != null)
{
enabled = true;
break;
}
else
{
MessageBox.Show("no");
}
}
}
else { MessageBox.Show("Error!"); }
And it immediately shows messagebox with "Error!" in it
Use linq to xml with Descendants:
Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection.(Inherited from XContainer.)
var abcs = XDocument.Load("data.xml").Descendants("ABC");
if(abcs.Any())
{
// There is at least one element of "ABC"
}
Related
This question already has answers here:
remove attribute if it exists from xmldocument
(2 answers)
Closed 4 years ago.
this is my XML
<root>
<CHILD ="1" UID="1">
<GrandChild>1</GrandChild>
</CHILD>
<CHILD ="2" UID="2">
<GrandChild>2</GrandChild>
</CHILD>
</root>
how can i remove child 1 from xml
Your xml is invalid because of the 'Child ="1"' syntax.
With valid xml you can parse using System.Xml.XmlDocument:
using System.Xml;
Create a new XmlDocument object:
XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
If you are reading xml from a file, use xmlDoc.Load(string filename):
xmlDoc.Load("yourXMLFile.xml");
If you are reading xml from a string, use xmlDoc.LoadXml(string xml):
xmlDoc.LoadXml(xmlStringVariable);
From there, you can parse through your XML by the tag names and child nodes. Here is a simple example, but hopefully it will give you a start:
XmlNodeList childList = xmlDoc.GetElementsByTagName("CHILD");
var _child = childList[0];
for (int i = 0; i < childList.Count; i++)
{
// Do work
// Loop through child nodes
for(int c = 0; c < childList[i].ChildNodes.Count; c++)
{
// Do something with child nodes
var _childNode = childList[i].ChildNodes[c].InnerXml;
}
}
This question already has answers here:
How does one parse XML files? [closed]
(12 answers)
XML Parsing - Read a Simple XML File and Retrieve Values
(5 answers)
Closed 5 years ago.
I have an XML file from which i have to extract only the attribute values in the tag. The XML kind of looks in this structure
<customer>
<customerMiddleInitial>W</customerMiddleInitial>
<name>
<FirstName>XXXXXXXX</FirstName>
<LastName> YYYYYYYY</LastName>
</name>
<customerBirth>1983-01-01</customerBirth>
<customerWorkPhone>020 1234567</customerWorkPhone>
<customerMobilePhone>0799 1234567</customerMobilePhone>
<previousCust>0</previousCust>
<timeOnFile>10</timeOnFile>
<customerId>CUST123</customerId>
</customer>
So, I want to extract all the details between the tags. The expected output should be all the customer details.
How can i implement this in C#?
Any help will be appreciated.
XmlDocument DOC = new XmlDocument();
DOC.Load("LoadYourXMLHere.xml");
XmlNodeList ParentNode = DOC.GetElementsByTagName("customer");
foreach (XmlNode AllNodes in ParentNode)
{
if (ParentNode == DOC.GetElementsByTagName("customerMiddleInitial"))
{
customer.Initial = AllNodes["customerMiddleInitial"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("name"))
{
customer.FirstName= AllNodes["FirstName"].InnerText;
customer.LastName= AllNodes["LastName"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerBirth"))
{
customer.Birthdate= AllNodes["customerBirth"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerWorkPhone"))
{
customer.WorkPhone= AllNodes["customerWorkPhone"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerMobilePhone"))
{
customer.MobilePhone = AllNodes["customerMobilePhone"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("previousCust"))
{
customer.PreviousCust= AllNodes["previousCust"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("timeOnFile"))
{
customer.TimeOnFile= AllNodes["timeOnFile"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerId"))
{
customer.ID= AllNodes["customerId"].InnerText;
}
}
Create a Customer model and execute the above xml parsing in C#.
Sincerely,
Thiyagu Rajendran
**Please mark the replies as answers if they help and unmark if they don't.
First of all you need to see this answer
When you generated model just use this code for deserialised xml to object.And after that just use model to work with your data. That is easy and simple
public static T FromXml<T>(String xml)
{
T returnedXmlClass = default(T);
try
{
using (TextReader reader = new StringReader(xml))
{
try
{
returnedXmlClass =
(T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
catch (InvalidOperationException)
{
// String passed is not XML, simply return defaultXmlClass
}
}
}
catch (Exception ex)
{
}
return returnedXmlClass;
}
and using
var model = FromXml<customer>(yourXmlString);
This question already has answers here:
SelectSingleNode returns null when tag contains xmlNamespace
(4 answers)
Closed 7 years ago.
I am using SelectNodes to read xml nodes but i am getting null when i try GetElementsByTagName i get the values.
XmlDocument xml = new XmlDocument();
xml.Load(DownloadFile);
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
for (int i = 0; i < xmlnode.Count; i++)
{
XmlNodeList rooms = xml .SelectNodes("RoomSize/CruisePriceSummaryRoomSize");
for(int j = 0; j < rooms.Count; j++)
{
string bestFare = rooms[j].SelectSingleNode("BestFare/TotalPrice").InnerText;
string fullFare = rooms[j].SelectSingleNode("FullFare/TotalPrice").InnerText;
// do whatever you need
}
}
I want to read TotalPrice from BestFare and FullFare Each child has two innerchilds BestFare and FullFareand I need to read each TotalPrice.
This is my XML
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCruisePriceSummaryResponse
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/OpenseasAPI.ServiceModel">
<CruisePriceSummaryResponse>
<AvailablePromos
xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>FLA</d3p1:string>
<d3p1:string>FLB</d3p1:string>
</AvailablePromos>
<Brand>PA</Brand>
<CruiseCategory i:nil="true"/>
<RoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>2798.0000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>3198.000000</TotalPrice>
</FullFare>
<PaxCount>2</PaxCount>
</CruisePriceSummaryRoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>2796.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>4196.000000</TotalPrice>
</FullFare>
<PaxCount>4</PaxCount>
</CruisePriceSummaryRoomSize>
</RoomSize>
<ShipCode>PD</ShipCode>
</CruisePriceSummaryResponse>
<CruisePriceSummaryResponse>
<AvailablePromos
xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>FLA</d3p1:string>
<d3p1:string>LF1</d3p1:string>
</AvailablePromos>
<Brand>PA</Brand>
<RoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>1298.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>3498.000000</TotalPrice>
</FullFare>
<PaxCount>2</PaxCount>
</CruisePriceSummaryRoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>1796.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>5396.000000</TotalPrice>
</FullFare>
<PaxCount>4</PaxCount>
</CruisePriceSummaryRoomSize>
</RoomSize>
<ShipCode>PJ</ShipCode>
</CruisePriceSummaryResponse>
</ArrayOfCruisePriceSummaryResponse>
Help would be appreciated. I do not want to use linq as this is a SSIS project using VS2008 and it doesnot support linq.
Thanks in advance
You never load or read the source XML. Your code
XmlDocument xml = new XmlDocument();
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
creates an empty XML document, and then tries to get elements from the empty xml.
You need to call XmlDocument.Load or XmlDocument.LoadXML to read the xml from a file or a string.
XmlDocument xml = new XmlDocument();
xml.Load("pathtosomefile.xml");
XmlNodeList xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
This question already has answers here:
How to Deserialize XML document
(16 answers)
Closed 8 years ago.
Given the following Xml:
<Student number='2020'>
<Subject>Comp</Subject>
<Credintials>
<Password>010101</Password>
<PasswordLength>6</PasswordLength>
<Contact>contact#example.com</Contact>
</Credintials>
<PersonalDetails age='30' height='2'/>
<Lecture age='30' height='2'>
<StudentName>Hakeem</StudentName>
</Lecture>
</Student>
I would want to print out the following list:
Student.#number=2020
Student.Subject=Comp
Student.Credintials.Password=010101
Student.Credintials.PasswordLength=6
Student.Credintials.Contact=contact#example.com
Student.PersonalDetails.#age=30
Student.Lecture.#age=30
Student.PersonalDetails.#height=2
Student.Lecture.#height=2
Student.Lecture.StudentName=Hakeem
I am basically trying to get these paths for attributes and elements which have their values equal to the innerText, elements like StudentName, Password, Subject. atttributes like age, height etc
Thanks
A method like this will print out what you expect
var xml = #"<Student number='2020'>
<Subject>Comp</Subject>
<Credintials>
<Password>010101</Password>
<PasswordLength>6</PasswordLength>
<Contact>contact#example.com</Contact>
</Credintials>
<PersonalDetails age='30' height='2'/>
<Lecture age='30' height='2'>
<StudentName>Hakeem</StudentName>
</Lecture>
</Student>";
var xmlParsed = XElement.Parse(xml);
GetNodeDescendantsAndPrint(xmlParsed);
public void GetNodeDescendantsAndPrint(XElement node, string nameToAppend= null)
{
var name = string.IsNullOrEmpty(nameToAppend)
? node.Name.LocalName
: nameToAppend;
foreach (var att in node.Attributes())
{
Console.WriteLine(name + ".#" + att.Name.LocalName + "=" + att.Value);
}
var descendants = node.Elements();
if (descendants.Any())
{
foreach (var innerNode in descendants.OfType<XElement>())
{
GetNodeDescendantsAndPrint(innerNode,
name+"." + innerNode.Name.LocalName );
}
}
else
{
Console.WriteLine(name + "=" + node.Value);
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why XDocument can’t get element out of this wellform XML text?
I'm trying to read an xml using linq to xml, and i guess i'm understanding something wrong.
This is the start of the xml (it's long so i'm not posting it all)
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<Body>
<ReportItems>
<Tablix Name="Tablix12">
......
......
</Tablix>
This xml could have a few of "Tablix" elements, and might have 1 or none, for each one of these i want to read whats inside this tag and i'm having difficulty to start.
I have tried a few ways to get the "Tablix" elements, or any other element.
In this code i get a result only for the "var root", the rest of them are always null and i don't understand what i'm doing wrong.
public ReadTablixResponse ReadTablixAdvanced(string rdl)
{
XDocument xml = XDocument.Parse(rdl);
var root = xml.Root;
var Body = xml.Root.Element("Body");
var report = xml.Root.Element("Report");
var aa = xml.Element("Report");
var bb = xml.Element("Body");
var test = xml.Elements("Tablix");
One thing i noticed, is that you used the method Element("name"). which will always try to retrun the first (in document order) direct child element with the specified XName . and that is probebly why you got null.
if you want to return deeper elements(from where you looking). you need to use the Descendants("name") method, which will return a collection of all descendants elements . no matter how deep they are (relative to your chosen anchor)...
for example:
XNamespace xNameSpace = "http://schemas.micro.....";
// ...
var tablixes= xml.Descendants(xNameSpace + "Tablix");
which you can then wolk through:
foreach (var tablix in tablixes)
{
var name=(string)tablix.Attribute("Name");
var age=(int)tablix.Element("age");
...
}
XDocument xDocument = XDocument.Parse(rdl);
XNamespace xNameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition";
var tablixes= from o in xDocument.Descendants(xNameSpace + "Tablix")
select o.Value;