Reading data from XML using C# - c#

I have to read the ordertext ("This is an example text") from this XML File:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<order id="">
<users>
<user id="123456" nick="nick" done="false" />
</users>
<machines>
<machine id="1234" sd="1234" ref="" done="false" />
</machines>
<todos />
<ordertexts>
<ordertext>This is an example text </ordertext>
</ordertexts>
</order>
My C# Code looks like this:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(file);
XmlElement node = (XmlElement)xDoc.SelectSingleNode("/order/ordertexts/ordertext");
When I write the selected data in another XML File it looks like this:
<order>
<oldOrderText>System.Xml.XmlElement</oldOrderText>
</order>
What did I do wrong? Is the XPath incorrect?
I am a C# newbie so I really need every help I can get!
Thanks in advance, geibi

What you're looking for is XmlElement.InnerText.
When you get the node using this:
XmlElement node = (XmlElement)xDoc.SelectSingleNode("/order/ordertexts/ordertext");
You still need to use this:
string neededText = node.InnerText;
to get the value of that node.
Suppose that you're writing the results in a console application. If you try to write the node variable, this way:
Console.WriteLine(node);
Since node is not a string, and it's an XmlElement object, the ToString method of XmlElement is going to be called, which returns the object name, hence your new XML had the result as System.Xml.XmlElement and not the desired text.

Related

Start reading from last value in xml

I have this kind of xml file. Root node is Sim and there are multiple "test" subnodes. Also each "test" has an instructor. Finally each instructor has own name,surname and rank values.
<Sim>
<Test ID="1" Description="test1" Date="17/01/2023">
<Instructor Num="1">
<Name>instructor1</Name>
<Surname></Surname>
<Rank></Rank>
</Instructor>
</Test>
<Test ID="2" Description="test2" Date="16/01/2023">
<Instructor Num="22">
<Name>instructor22</Name>
<Surname></Surname>
<Rank></Rank>
</Instructor>
</Test>
</Sim>
With xelement.load, the test ids of this file are read as they are in the file. I want xelement.load to read after test ids are sorted from largest to smallest. How can i do this? instructor part is also included in second code.
<Sim>
<Test ID="3" Description="test3" Date="18/01/2023"></Test>
<Test ID="2" Description="test2" Date="17/01/2023"></Test>
<Test ID="1" Description="test1" Date="16/01/2023"></Test>
</Sim>
Try with XDocument and LINQ
var xDoc = XDocument.Parse(File.ReadAllText("XMLFile2.xml"));
var elements = xDoc.Descendants("Test").OrderByDescending(x=> Convert.ToInt16(x.Attribute("ID").Value));

How to I write the contents of XML file(XmlDocument) to text file?

I've xml data inside a local variable xml of type XMLDocument
I wish to save the xml data as it is into a local file.
I've tried something like System.IO.File.WriteAllText(#"C:\MyProfile\OutOut.txt", xml.ToString()); but doesn't work.
Can someone let me know how to proceed for this?
Also let me now if any additional data is needed.
Thanks.
**Update: ** The above task was accomplished by using XmlDocument.Save(FilePath); now just a small update to the questio is like :
If I have to save only a specific parent node along with it's child nodes, how do I proceed
Sample xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Master Name="Accounts">
<Employee>
<Section>
<Details>
<Name="abc" ID="68" PF="9999" />
</Details>
<Department DeptId="12" />
</Section>
<Section>
<Details>
<Name="xyz" ID="69" PF="9999" />
</Details>
<Department DeptId="13" />
</Section>
</Employee>
</Master>
Only Node <Employee> and it's children.
This code converts XmlDocument to text:
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}

How to extract a node from xml string C#

I have am xml string like mentioned below:
<?xml version="1.0" encoding="utf-8" ?>
<NodeA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.air-watch.com/webapi/resources">
<AdditionalInfo>
<Links>
<Link xsi:type="link">
</Link>
</Links>
</AdditionalInfo>
<TotalResults>100</TotalResults>
<NodeB>
<NodeC>
<Id>1</Id>
<A>valueA</A>
<B>valueB</B>
</NodeC>
<NodeC>
<Id>2</Id>
<A>valueA</A>
<B>valueA</B>
</NodeC>
</NodeB>
</NodeA>
I want to extract NodeB and its child nodes (NodeC elements). How can I do it? Below solution does somewhat similar operation but it needs the xml string to be loaded in a XDocument first:
XDocument doc=XDocument.Parse(xmlstr);
String response=doc.Elements("question")
.Where(x=>x.Attribute("id")==id)
.Single()
.Element("response")
.Value;
Is there a way to do it without having to load it in a doc? Some operation on string object itself.
Why cant you use this
XDocument doc=XDocument.Parse(xmlstr);
String response=doc.Elements("question")
.Where(x=>x.Attribute("id")==id)
.Single()
.Element("response")
.Value; ?
you can use Regular Expressions then.

How to insert a child element into an existing element

I am using a XDocument to write an xml file and I am writing to the document in two different places. After the first write I have
<?xml version="1.0" encoding="utf-8"?>
<suspensedata connectionid="000" customerid="000" name="MyName" />
After the second write I want the file to look like this
<?xml version="1.0" encoding="utf-8"?>
<suspensedata connectionid="560" customerid="131" name="ImgTransfer2327">
<transaction DocumentID="46" SuspenseID="7">
<field id="LocationID">000000015000</field>
<field id="AccountNumber">50000</field>
<field id="AmountPaid">25.00</field>
<field id="CheckAmount">100.00</field>
<field id="CheckNo">000</field>
</transaction>
</suspensedata>
But I can't seem to get the insert done correctly.
I've tried (The name of my XDocument is ValidXml) ValidXml.Root.Add(new Element("transaction"));
and that does not change anything.
I have also tried ValidXml.Element("suspensedata").Add(new XElement("transaction"));
But that did not work either.
How would I add this child element?
EDIT: Both attempts did not produce any other output besides the output on the first try. Also I did make sure to use ValidXml.Save()
I have tried something like this I supposed that the two parts are in 2 files
//xmlfile1 contains the first part
<?xml version="1.0" encoding="utf-8"?>
<suspensedata connectionid="000" customerid="000" name="MyName" />
//this part will be loaded like this
XDocument xDoc = XDocument.Load("xmlfile1.xml");
XElement elt = xDoc.Root;
//and the second file contains the second part
XDocument xDoc2 = XDocument.Load("xmlfile2.xml");
XElement elt2 = xDoc2.Root;
elt.Add(elt2);
xDoc.Save("xmlfile1.xml");
Hope this help

How to read nested XML using xDocument in Silver light?

Hi currently I have a nested XMl , having the following Structure :
<?xml version="1.0" encoding="utf-8" ?>
<Response>
<Result>
<item id="something" />
<price na="something" />
<?xml version="1.0" encoding="UTF-8" ?>
<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/">
</Result>
<NumberReturned>10</NumberReturned>
<TotalMatches>10</TotalMatches>
</Response>
Any help on how to read this using Xdocument or XMLReader will be really helpfull.
Thanks,
Subhendu
XDocument and XmlReader are both XML parsers that expect a properly formed XML as input. What you have shown is not a XML file. So the first task would be to extract the nested XML and as this is not valid XML you cannot rely on any parser to do this job. You'll need to resort to string manipulation and or regular expressions.
My suggestion would be to fix the procedure generating this invalid XML in the first place. Another suggestion is to never generate a XML file manually but use an appropriate tool for this (XmlWriter, XDocument, ...)

Categories