Traversing through xml file - c#

I have XML like this.
<?xml version="1.0" encoding="utf-8" ?>
<config>
<atag>
<element1 att="value" />
<element2 att="othervalue"/>
</atag>
<othertag>
<element1 att="value" />
<element2 att="othervalue"/>
</othertag>
</config>
I want to traverse through the file and find "element1" tag and raplce it with "abc" tag.
Please help. Thank You in advance
In the same file I want to store att value in an array first then raplace the tag name to "abc" . Please help me out

var xml = XDocument.Load(fileName);
foreach (var e in xml.Root.Elements().SelectMany(x => x.Elements("element1")))
{
e.Name = "abc";
}
xml.Save(fileName);

Related

c# xml linq correct way?

i read about Linq and xml, but i dont know if i do it the right way...
here my XML Configuration File:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Priorities>
<Priority Index="0">Zero</Priority>
<Priority Index="1">One</Priority>
<Priority Index="2">Two</Priority>
<Settings>
<Name>PriorityName</Name>
<DisplayName>PriorityDisplayName</DisplayName>
<Active>true</Active>
<Index>0</Index>
</Settings>
</Priorities>
<Workcenters>
<Workcenter Index="0">TEAM_0</Workcenter>
<Workcenter Index="1">TEAM_1</Workcenter>
<Workcenter Index="2">TEAM_2</Workcenter>
<Settings>
<Name>WorkcentersName</Name>
<DisplayName>WorkcentersDisplayName</DisplayName>
<Active>false</Active>
<Index>1</Index>
</Settings>
</Workcenters>
<ErrorPages>
<ErrorPage>
<Name>Error_1</Name>
<Type>Critical</Type>
</ErrorPage>
<ErrorPage>
<Name>Error_2</Name>
<Type>Normal</Type>
</ErrorPage>
</ErrorPages>
</Configuration>
Now i access all Priorities like this:
//Get Prios
XElement xelement = XElement.Load(xmlPath2);
IEnumerable<XElement> priorities = xelement.Descendants("Priorities");
var prios = priorities.Elements("Priority").ToList();
var settings = priorities.Elements("Settings");
foreach (XElement priority in prios)
{
Console.WriteLine(priority.Attribute("Index").Value);
Console.WriteLine(priority.Value);
}
foreach (XElement setting in settings)
{
Console.WriteLine(setting.Element("Name").Value);
Console.WriteLine(setting.Element("Active").Value);
Console.WriteLine(setting.Element("Index").Value);
Console.WriteLine(setting.Element("DisplayName").Value);
}
is this the right way to access the Elements?
i think there will be a better to read solution.
Can u help me?
thanks
You could use XPathSelectElements extension method.
So your code would look something like:
XElement xelement = XElement.Load(xmlPath2);
foreach (XElement priority in xelement.XPathSelectElements("Priorities/Priority"))
{
Console.WriteLine(priority.Attribute("Index").Value);
Console.WriteLine(priority.Value);
}
foreach (XElement setting in xelement.XPathSelectElements("Priorities/Settings"))
{
Console.WriteLine(setting.Element("Name").Value);
Console.WriteLine(setting.Element("Active").Value);
Console.WriteLine(setting.Element("Index").Value);
Console.WriteLine(setting.Element("DisplayName").Value);
}

How to get enclosure url with XElement C# Console

I read multiple feed from many sources with C# Console, and i have this code where i load XML From sources:
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
XElement xdoc = XElement.Load(sourceURLX);
How to get enclosure url and show as variable?
If I understand your question correctly (I'm making a big assumption here) - you want to select an attribute from the root (or 'enclosing') tag, named 'url'?
You can make use of XPath queries here. Consider the following XML:
<?xml version="1.0" encoding="utf-8"?>
<root url='google.com'>
<inner />
</root>
You could use the following code to retrieve 'google.com':
String query = "/root[1]/#url";
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
String value = doc.SelectSingleNode(query).InnerText;
Further information about XPath syntax can be found here.
Edit: As you stated in your comment, you are working with the following XML:
<item>
<description>
</description>
<enclosure url="blablabla.com/img.jpg" />
</item>
Therefore, you can retrieve the url using the following XPath query:
/item[1]/enclosure[1]/#url
With xml like below
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>title</title>
<link>https://www.link.com</link>
<description>description</description>
<item>
<title>RSS</title>
<link>https://www.link.com/xml/xml_rss.asp</link>
<description>description</description>
<enclosure url="https://www.link.com/media/test.wmv"
length="10000"
type="video/wmv"/>
</item>
</channel>
</rss>
You will get url by reading attribute
var document = XDocument.Load(sourceURLX);
var url = document.Root
.Element("channel")
.Element("item")
.Element("enclosure")
.Attribute("url")
.Value;
To get multiple urls
var urls = document.Descendants("item")
.Select(item => item.Element("enclosure").Attribute("url").Value)
.ToList();
Using foreach loop
foreach (var item in document.Descendants("item"))
{
var title = item.Element("title").Value;
var link = item.Element("link").Value;
var description = item.Element("description").Value;
var url = item.Element("enclosure").Attribute("url").Value;
// save values to database
}

how to save the results of XPathSelectElements to xml in C#

I have an XML file and I wanna extract some elements using XPathSelectElements("..."). It works fine but I have no idea how to save the extracted data into a new XML file with a new outer wrap
Here's what I've got, XPathSelectElements works fine:
var doc = XDocument.Load("XXX.xml");
var nData = doc.XPathSelectElements("Orders/Order[#ID > 1]");
//code to save data to a new file...
My original xml file is like this:
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<Order ID="1">aaa</Order>
<Order ID="2">bbb</Order>
<Order ID="3">ccc</Order>
</Orders>
And I wanna save the result to a new xml file and with an extra wrap like this:
<?xml version="1.0" encoding="utf-8"?>
<newWrap>
<Orders>
<Order ID="2">bbb</Order>
<Order ID="3">ccc</Order>
</Orders>
</newWrap>
Any help? Thanks a lot~
This is one possible way :
var nData = doc.XPathSelectElements("Orders/Order[#ID > 1]");
var root = new XElement("newWrap",
new XElement("Orders", nData)
);
var newDoc = new XDocument(root);
newDoc.Save("new_file.xml");
Dotnetfiddle Demo

Add XML element before last element using Linq

I need to add new element before the last element of the XML using Linq.
For example:
<?xml version="1.0" encoding="utf-8"?>
<products>
<product id="p1">
<name>Delta</name>
<price>800</price>
<country>Denmark</country>
</product>
<product id="p3">
<name>Alfa</name>
<price>1200</price>
<country>Germany</country>
</product>
</products>
New element <stock></stock> should be inserted before <country> element using Linq
// load the XML file into XDocument instance
var doc = XDocument.Load("sourceFile.xml");
// find all <country> elements
var countries = doc.Root.Elements("product").Elements("Country");
// add <stock /> before each <country> elements
foreach(var country in countries)
{
country.AddBeforeSelf(new XElement("stock"));
}
// save document to the file
doc.Save("sourceFile.xml");

How to extract a part of xml code from an xml file using c# code

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<eRecon xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="eRecon.xsd">
<Header>
<Company Code="" />
<CommonCarrierCode />
<InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName>
<BatchNumber>000152</BatchNumber>
<InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime>
<InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime>
<RecordCount>8</RecordCount>
</Header>
<Detail>
<CarrierStatusDate>2010-01-11</CarrierStatusDate>
<ClaimNum>YDF02892 C</ClaimNum>
<InvoiceNum>0108013775</InvoiceNum>
<LineItemNum>001</LineItemNum>
<NABP>10600211</NABP>
<RxNumber>4695045</RxNumber>
<RxDate>2008-07-21</RxDate>
<CheckNum />
<PaymentStatus>PENDING</PaymentStatus>
<RejectDescription />
<InvoiceChargeAmount>152.15</InvoiceChargeAmount>
<InvoicePaidAmount>131.00</InvoicePaidAmount>
</Detail>
</eRecon>
How can I extract the portion
<Header>
<Company Code="" />
<CommonCarrierCode />
<InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName>
<BatchNumber>000152</BatchNumber>
<InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime>
<InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime>
<RecordCount>8</RecordCount>
</Header>
from the above xml file.
I need the c# code to extract a part of xml tag from an xml file.
If the file isn't too big (smaller than a few MB), you can load it into an XmlDocument:
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\yourfile.xml");
and then you can parse for the <Header> element using an XPath expression:
XmlNode headerNode = doc.SelectSingleNode("/eRecon/Header");
if(headerNode != null)
{
string headerNodeXml = headerNode.OuterXml;
}
You can use XPath like in this tutorial:
http://www.codeproject.com/KB/cpp/myXPath.aspx
Use Linq-to-xml:
XDocument xmlDoc = XDocument.Load(#"c:\sample.xml");
var header = xmlDoc.Descendants("Header").FirstOrDefault();
Linq version
string fileName=#"d:\xml.xml";
var descendants = from i in XDocument.Load(fileName).Descendants("Header")
select i;

Categories

Resources