Reading xml data from file on desktop - c#

Hello and today I want to find out how I can read an xml file in the following way, I have not been able to find ANYTHING like this or anythig simulaur to how I want to do this that works. I have an xml file with the following content format that has been disabled below this.
<smallusers>
<user id="1">
<name>John</name>
<motto>I am john, who are you?</motto>
</user>
<user id="2">
<name>Peter</name>
<motto>Hello everyone!</motto>
</user>
</smallusers>
<bigusers>
<user id="3">
<name>Barry</name>
<motto>Earth is awesome</motto>
</user>
</bigusers>
How can I put that into 2 string lists in csharp

Load it as a text file into a string or StringBuilder.
prefix it with <xml> and end it with </xml>
then use XmlDocument to load your xml

XML can have only one root tag. You input has more than one root. So you have to wrap your XML in a root like code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
string input = File.ReadAllText(FILENAME);
input = string.Format("<Root>{0}</Root>", input);
XElement root = XElement.Parse(input);
}
}
}
​

Related

Update a specific node in XML using XmlDocument

I am new to managing XML, I've read a couple of articles but I'm confused when it comes to a specific XML that I am working on. Can someone help me with the right statement? I just want to update the value of the ListStart, but I am getting an error when compiling. I am updating that part by this:
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.Load(#"path");
XmlNode myNode = soapEnvelopeDocument.SelectSingleNode("descendant::cet:GetListCustomElement[cet:GetListCustom/cet:ListID='101']");
soapEnvelopeDocument.LastChild.InnerText = sDate;
<soapenv:Header/>
<soapenv:Body>
<cet:GetListCustomElement>
<!--Zero or more repetitions:-->
<cet:GetListCustom>
<cet:ListID>101</cet:ListID>
<cet:ListStart>13.11.2020</cet:ListStart>
</cet:GetListCustom>
</cet:GetListCustomElement>
</soapenv:Body>
</soapenv:Envelope>```
You only supplied a piece of the xml without the namespaces. With Xml linq you can get the element without the namespaces. See code below :
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);
XElement ListStart = doc.Descendants().Where(x => x.Name.LocalName == "ListStart").FirstOrDefault();
ListStart.SetValue("14.11.2020");
}
}
}

I need to read xml file data but due to attribute it does not work

i want to read xml file but due to Document node attribute it did not read file.
Code C#:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(HttpContext.Server.MapPath("~/Content/Images/MMS-CREATE-ALLA-ALLAH2H1-23102018-000170-INP.xml"));
XmlNode settings = xmldoc.SelectSingleNode("Document[#xmlns='urn:iso:std:iso:20022:tech:xsd:pain.009.001.01']/MndtInitnReq/GrpHdr");
stu.BranchName = settings.SelectSingleNode("MsgId").InnerText;
XML FIle:
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.009.001.01">
<MndtInitnReq>
<GrpHdr>
<MsgId>10005226074</MsgId>
<CreDtTm>2018-10-23T15:20:56</CreDtTm>
</GrpHdr>
</MndtInitnReq>
</Document>
You have a namespace that must be used to get the data. Try Xml Linq :
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication75
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = doc.Root.GetDefaultNamespace();
string msgId = (string)doc.Descendants(ns + "MsgId").FirstOrDefault();
XElement xCreDtTm = doc.Descendants(ns + "CreDtTm").FirstOrDefault();
//will give 1/1/01 when null
DateTime CreDtTm = xCreDtTm == null ? new DateTime() : (DateTime)xCreDtTm;
}
}
}
I don't think loading this xml should be a problem. I verified that by loading the xml you posted in an XmlDocument object.
However I think, your xpath to get "settings" node should have xml namespace in all tags after Document.
So the xpath should be "/[local-name()='Document' and namespace-uri()='urn:iso:std:iso:20022:tech:xsd:pain.009.001.01']/[local-name()='MndtInitnReq' and namespace-uri()='urn:iso:std:iso:20022:tech:xsd:pain.009.001.01']/*[local-name()='GrpHdr' and namespace-uri()='urn:iso:std:iso:20022:tech:xsd:pain.009.001.01']"

Read content from the xml file in C#

i want to read content form xml file in the below format in c# . Please let me know
<Company>
<Employee>
<FirstName>FN</FirstName>
<LastName>LN</LastName>
</Employee>
<Employee>
<FirstName>FN1</FirstName>
<LastName>SN1</LastName>
</Employee>
</Company>
Use xml linq like code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication58
{
class Program
{
const string FILENAME = #"C:\TEMP\TEST.XML";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<KeyValuePair<string, string>> names = doc.Descendants("Employee")
.Select(x => new KeyValuePair<string, string>((string)x.Element("FirstName"), (string)x.Element("LastName")))
.ToList();
}
}
}

XmlDocument rearrange XmlNodes C#

I have an XML Document that stores all sorts of information about users of a system. Utlimately, the nodes that I am intersted in I hae outined below.
So, there is a user that has many user contents - I have included just books as an example.
<?xml version="1.0" encoding="UTF-8"?>
<user>
<userProperties>
<alias val="userAliasOne"/>
<id val="3423423"/>
</userProperties>
<userContent>
<userBooks>
<genre>
<book>
<title>Dummy Value</title>
</book>
</genre>
</userBooks>
</userContent>
</user>
I need to somehow restructure the XML, using XmlDocument and XmlNode so that it matches the below. (userBooks to become root node but all contents of userBooks - /genre/book/title - to stay inside userContent).
<?xml version="1.0" encoding="UTF-8"?>
<userBooks>
<user>
<userProperties>
<alias val="userAliasOne"/>
<id val="3423423"/>
</userProperties>
<userContent>
<genre>
<book>
<title>Dummy Value</title>
</book>
</genre>
</userContent>
</user>
</userBooks>
I've tried selecting the single nodes and cloning them, then appending the clone to the parent and removing the child that's no longer required. It became very long and convoluted and I couldn't get it to work. There must be a more elegant solution that I am not aware of.
Any help appreciated.
Thanks.
Using XML Linq
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);
List<XElement> userBooks = doc.Descendants("userBooks").ToList();
foreach(XElement userBook in userBooks)
{
userBook.ReplaceWith(userBook.Element("genre"));
}
}
}
}
​
Here's an example for adding a new root element:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
var originalRoot = doc.DocumentElement;
doc.RemoveChild(originalRoot);
var newRoot = doc.CreateElement("userBooks");
doc.AppendChild(newRoot);
newRoot.AppendChild(originalRoot);
doc.Save(Console.Out);
}
}
Try using the same approach for "removing" the userBooks element in the original - remove the element from its parent, but then add all the child nodes (of userBooks) as new child nodes of the original parent of userBooks.

How do I connect with other xml file xml file

I have two XML files using the XML data processing files How do I connect them to each other?
Example:
members.xml
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<member id="1" username="selahattin" name="Selahattin" surname="Yüksel"/>
<member id="2" username="test" name="John" surname="Bravo"/>
</Data>
comments.xml
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<member id="1" username="selahattin" comment="Hi, stackoverflow"/>
<member id="2" username="test" comment="Hello world!"/>
</Data>
Using two XML files in the username field of the data How do you want to take this?
username==username
here is one method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME1 = #"c:\temp\test.xml";
const string FILENAME2 = #"c:\temp\test2.xml";
static void Main(string[] args)
{
DataSet ds1 = new DataSet();
ds1.ReadXml(FILENAME1);
DataSet ds2 = new DataSet();
ds2.ReadXml(FILENAME2);
var results = from dataRows1 in ds1.Tables["member"].AsEnumerable()
join dataRows2 in ds2.Tables["member"].AsEnumerable()
on dataRows1.Field<string>("id") equals dataRows2.Field<string>("id") into ps
select dataRows1;
DataTable combinedTable = results.CopyToDataTable();
}
}
}​

Categories

Resources