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
Related
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
}
I have a collection string with information about customers like name, gender etc. All custumers have an id.
Now i want to create a common XML file with all customers in it. Something like example below:
<custumers>
<custumer>
<name></name>
<id></id>
<etc></etc>
</custumer>
</custumers>
The start up with no XML file is easy, I used linq to create the xml file.
For initial creation I used following code:
try
{
var xEle = new XElement("Customers",
from cus in cusList
select new XElement("Customer",
new XElement("Name", cus.Name),
new XElement("gender", cus.gender),
new XElement("etc", cus.etc));
}
xEle.Save(path);
But on the point if i want to update the XML file i get some problems to get it.
My approach to solve it:
Iterate over all customers in list and check for all customers if the customer.id exists in the XML.
IF not: add new customer to xml
IF yes: update values
My code so far:
var xEle = XDocument.Load(xmlfile);
foreach (cus in cusList)
try
{
var cids = from cid in xEle.Descendants("ID")
where Int32.Parse(xid.Element("ID").Value) == cus.ID
select new XElement("customer", cus.name),
new XElement ("gender"), cus.gender),
new XELement ("etc."), cus.etc)
);
xEle.Save(xmlpath);
}
How about a different approach....
using System.IO;
using System.Text;
using System.Xml.Serialization;
public void Main()
{
DataSet Custumers = new DataSet("Custumers");
DataTable Custumer = new DataTable("Custumer");
// Create the columns
Custumer.Columns.Add("id", typeof(int)).Unique = true;
Custumer.Columns.Add("name", typeof(string));
Custumer.Columns.Add("gender", typeof(string));
Custumer.Columns.Add("etc", typeof(string));
// Set the primary key
Custumer.PrimaryKey = { Custumer.Columns("id") };
// Add table to dataset
Custumers.Tables.Add(Custumer);
Custumers.AcceptChanges();
// Add a couple of rows
Custumer.Rows.Add(1, "John", "male", "whatever");
Custumer.Rows.Add(2, "Jane", "female", "whatever");
Custumer.AcceptChanges();
// Let's save this to compare to the updated version
Custumers.WriteXml("Custumers_Original.xml");
// Read in XML that contains an existing Custumer and adds a new one
// into a Clone of the Custumer table
DataTable CustumerUpdate = Custumer.Clone;
CustumerUpdate.ReadXml("Custumers_Update.xml");
// Merge the clone table data to the Custumer table
Custumer.Merge(CustumerUpdate);
Custumer.AcceptChanges();
Custumers.WriteXml("Custumers_Final.xml");
}
Custumers_Original.xml looks like this:
<?xml version="1.0" standalone="yes"?>
<Custumers>
<Custumer>
<id>1</id>
<name>John</name>
<gender>male</gender>
<etc>whatever</etc>
</Custumer>
<Custumer>
<id>2</id>
<name>Jane</name>
<gender>female</gender>
<etc>whatever</etc>
</Custumer>
</Custumers>
Custumers_Update.xml has this, making a change to John and adding George:
<?xml version="1.0" encoding="utf-8" ?>
<Custumers>
<Custumer>
<name>John</name>
<id>1</id>
<gender>male</gender>
<etc>this is new</etc>
</Custumer>
<Custumer>
<name>George</name>
<id>3</id>
<gender>male</gender>
<etc>grandson</etc>
</Custumer>
</Custumers>
After the merge, the Custumers_Final.xml contains this:
<?xml version="1.0" standalone="yes"?>
<Custumers>
<Custumer>
<id>1</id>
<name>John</name>
<gender>male</gender>
<etc>this is new</etc>
</Custumer>
<Custumer>
<id>2</id>
<name>Jane</name>
<gender>female</gender>
<etc>whatever</etc>
</Custumer>
<Custumer>
<id>3</id>
<name>George</name>
<gender>male</gender>
<etc>grandson</etc>
</Custumer>
</Custumers>
Also my solution with linq:
try
{
XDocument xEle = XDocument.Load(path);
var ids = from id in xEle.Descendants("Custom")
where id.Element("id").Value == cus.ID
select id;
foreach (XElement idCustom in ids)
{
idCustom.SetElementValue("NewName", "NewElement");
}
xEle.Save(path);
}
How do I get the innertext of the OverallResult element using SelectSingleNode?
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessResp xmlns="http://www.w3.org/2005/Atom">
<Result>
<OverallResult>Success</OverallResult>
var doc = new XmlDocument();
doc.LoadXml(xml);
var text = doc.SelectSingleNode("Example/Node/text()").InnerText; // or .Value
returns
"Some text here\r\n "
and text.Trim() returns
"Some text here"
Please go through the below link for XML related queries its very useful for begginers!
http://www.dotnetcurry.com/ShowArticle.aspx?ID=564
for your answer(i havnt tried it though try by changing like this in ur code)
doc.SelectSingleNode("soap/ProcessResp/ Result/OverallResult/text()").InnerText;
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");
I have some XML and need to be able to read the data within.
A sample of the XML is
<?xml version="1.0" ?>
<ConsumeLeadRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<LeadType>Mortgage</LeadType>
<LeadXml>
<ns1:LeadAssigned xmlns:ns1="http://YaddaYadda" xmlns:ns0="http://YaddaYadda" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns0:Lead>
<Reference>1234</Reference>
<Product>
<Mnemonic>Mortgage</Mnemonic>
<Description>Mortgage Leads</Description>
<SubType>Other</SubType>
</Product>
<ExtendedInfo>
<Mortgage>
<MortgageValue>75000</MortgageValue>
<MortgageValueLowerBound>1</MortgageValueLowerBound>
<MortgageValueUpperBound>500</MortgageValueUpperBound>
<PropertyValue>100000</PropertyValue>
<PropertyValueLowerBound>1</PropertyValueLowerBound>
<PropertyValueUpperBound>500</PropertyValueUpperBound>
<Adverse>false</Adverse>
<FirstTime>false</FirstTime>
</Mortgage>
</ExtendedInfo>
<Applicants>
<Applicant1>
<Title>Mr</Title>
<Forename>SampleForename</Forename>
<Surname>SampleSurname</Surname>
<DateOfBirth>1903-02-01</DateOfBirth>
<Smoker>false</Smoker>
<TelephoneNumbers>
<TelephoneNumber>
<Number>01244123456</Number>
<Type>Mobile</Type>
</TelephoneNumber>
</TelephoneNumbers>
<EmailAddresses>
<EmailAddress>
<Email>test#moneysupermarket.com</Email>
<Type>Business</Type>
</EmailAddress>
</EmailAddresses>
<Addresses>
<Address>
<Street>Sample Street</Street>
<District>Sample District</District>
<Town>Sample Town</Town>
<County>Sample County</County>
<Postcode>CH53UZ</Postcode>
<Type>Home</Type>
</Address>
</Addresses>
</Applicant1>
</Applicants>
</ns0:Lead>
<Assignment>
<Price>20</Price>
<AssignmentDateTime>2010-02-01T00:00:00</AssignmentDateTime>
<Subscription>
<Reference>1234</Reference>
<Subscriber>
<Title>Mr</Title>
<Forename>SampleForename</Forename>
<Surname>SampleSurname</Surname>
</Subscriber>
</Subscription>
<Account>
<Reference>1234</Reference>
<CompanyName>Sample Company</CompanyName>
</Account>
<LeadType>SampleLeadType</LeadType>
<TerritoryName>UNITED KINGDOM</TerritoryName>
</Assignment>
</ns1:LeadAssigned>
</LeadXml>
<AuthenticationUsername>Username</AuthenticationUsername>
<AuthenticationPassword>Password</AuthenticationPassword>
</ConsumeLeadRequest>
Using Linq to XML how do i navigate to the items?
Thanks
Sp
I have tried a few things like
XDocument Leads = XDocument.Load(#"C:\Users\Steven.Pentleton\AppData\Local\Temporary Projects\PAALeadImport\PAAExmple.xml");
var Lead = (from L in Leads.Descendants("Lead")
select new { LeadType = (string)L.Element("Reference") }).ToList();
var S = Lead.First();
string T = S.LeadType;
Are you looking for XDcoument or XElement in linq
Namespace: using System.Xml.Linq;
I guess you are looking for a Linq To Xml guide