Extract a node from xml response - c#

Below is my response generated from a webservice.
I want to do such that I want only PresentationElements node from this response.
Any help how can I achieve this query?
<?xml version="1.0"?>
<GetContentResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ExtensionData />
<GetContentResult>
<ExtensionData />
<Code>0</Code>
<Value>Success</Value>
</GetContentResult>
<PresentationElements>
<PresentationElement>
<ExtensionData />
<ContentReference>Product View Pack</ContentReference>
<ID>SHOPPING_ELEMENT:10400044</ID>
<Name>View Pack PE</Name>
<PresentationContents>
<PresentationContent>
<ExtensionData />
<Content>View Pack</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Name</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>Have more control of your home's security and lighting with View Pack from XFINITY Home.</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Description</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>/images/shopping/devices/xh/view-pack-2.jpg</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Image</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>The View Pack includes:
2 Lighting / Appliance Controllers
2 Indoor / Outdoor Cameras</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Feature1</Name>
</PresentationContent>
</PresentationContents>
</PresentationElement>
</PresentationElements>
</GetContentResponse>

You can use XPath extensions
var xdoc = XDocument.Parse(response);
XElement presentations = xdoc.XPathSelectElement("//PresentationElements");

You may use the System.Xml.Linq.XDocument:
//Initialize the XDocument
XDocument doc = XDocument.Parse(yourString);
//your query
var desiredNodes = doc.Descendants("PresentationElements");

Pretty easy, have you tried:
XDocument xml = XDocument.Load("... xml");
var nodes = (from n in xml.Descendants("PresentationElements")
select n).ToList();
You could also project each individual node to an anonymous type using something like:
select new
{
ContentReference = (string)n.Element("ContentReference").Value,
.... etc
}

Related

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
}

Reading child nodes from xml string using C#, LINQ

- <entry xml:base="http://testserver.windows.net/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:etag="W/"datetime'2015-08-30T00%3A04%3A02.9193525Z'"">
<id>http://testserver.windows.net/Players(PartitionKey='zzz',RowKey='000125')</id>
<category term="testServer.Players" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
<link rel="edit" title="Players" href="Players(PartitionKey='zzz',RowKey='000125')" />
<title />
<updated>2014-04-30T00:53:42Z</updated>
- <author>
<name />
</author>
- <content type="application/xml">
- <m:properties>
<d:PartitionKey>zzz</d:PartitionKey>
<d:RowKey>000125</d:RowKey>
<d:Timestamp m:type="Edm.DateTime">2014-04-30T00:04:02.9193525Z</d:Timestamp>
<d:Name>Black color</d:Name>
<d:Comments>Test comments</d:Comments>
</m:properties>
</content>
</entry>
How can I read "m:properties" descendants using C# or LINQ.
This xml string is stored in variable of type XElement
You can use combination of XNamespace+"element local name" to reference element in namespace, for example :
XElement myxelement = XElement.Parse("your XML string here");
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
List<XElement> properties = myxelement.Descendants(m+"properties").ToList();
I think this could show you how to use Linq to XML
read the data from XML Structure using c#
If anything else makes problems, just debug a little, see what you get from L2X operation, and move a step deeper trough data tree.
Using Linq2XML
var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("m:properties")
.First()
.Attributes()
.ToDictionary(x => x.Name, x => x.Value);
Setup namespace manager. Note that .net library does not support default namespace, so I added prefix "ns" to default namespace.
use xpath or linq to query xml. Following example uses xpath.
XmlNamespaceManager NamespaceManager = new XmlNamespaceManager(new NameTable());
NamespaceManager.AddNamespace("base", "http://testserver.windows.net/");
NamespaceManager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
NamespaceManager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
NamespaceManager.AddNamespace("ns", "http://www.w3.org/2005/Atom"); XDocument doc = XDocument.Parse(XElement);
var properties = doc.XPathSelectElement("/ns:entry/ns:content/m:properties", NamespaceManager);

Read xml descendants collection from xml string [duplicate]

- <entry xml:base="http://testserver.windows.net/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:etag="W/"datetime'2015-08-30T00%3A04%3A02.9193525Z'"">
<id>http://testserver.windows.net/Players(PartitionKey='zzz',RowKey='000125')</id>
<category term="testServer.Players" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
<link rel="edit" title="Players" href="Players(PartitionKey='zzz',RowKey='000125')" />
<title />
<updated>2014-04-30T00:53:42Z</updated>
- <author>
<name />
</author>
- <content type="application/xml">
- <m:properties>
<d:PartitionKey>zzz</d:PartitionKey>
<d:RowKey>000125</d:RowKey>
<d:Timestamp m:type="Edm.DateTime">2014-04-30T00:04:02.9193525Z</d:Timestamp>
<d:Name>Black color</d:Name>
<d:Comments>Test comments</d:Comments>
</m:properties>
</content>
</entry>
How can I read "m:properties" descendants using C# or LINQ.
This xml string is stored in variable of type XElement
You can use combination of XNamespace+"element local name" to reference element in namespace, for example :
XElement myxelement = XElement.Parse("your XML string here");
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
List<XElement> properties = myxelement.Descendants(m+"properties").ToList();
I think this could show you how to use Linq to XML
read the data from XML Structure using c#
If anything else makes problems, just debug a little, see what you get from L2X operation, and move a step deeper trough data tree.
Using Linq2XML
var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("m:properties")
.First()
.Attributes()
.ToDictionary(x => x.Name, x => x.Value);
Setup namespace manager. Note that .net library does not support default namespace, so I added prefix "ns" to default namespace.
use xpath or linq to query xml. Following example uses xpath.
XmlNamespaceManager NamespaceManager = new XmlNamespaceManager(new NameTable());
NamespaceManager.AddNamespace("base", "http://testserver.windows.net/");
NamespaceManager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
NamespaceManager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
NamespaceManager.AddNamespace("ns", "http://www.w3.org/2005/Atom"); XDocument doc = XDocument.Parse(XElement);
var properties = doc.XPathSelectElement("/ns:entry/ns:content/m:properties", NamespaceManager);

How to modify an external xml file and save it locally in C#

I'm new to C# and want to manipulate a external xml file. Here is that file:
<results>
<root />
<category id="" title="" />
<category />
<category />
</results>
I want this to be modified something like:
<results>
<root />
<categories>
<category id="" title=""/>
<category />
<category />
</categories>
</results>
This works, it replaces all of the elements named category found directly under the root element (root element is results) and adds new element named categories. category elements are then added to categories and category elements are removed from under the results element. In the end categories element is added. You can also save the document by calling it's Save method:
XDocument doc = XDocument.Load("Data.xml");
var categoriesElement = new XElement("categories");
var categoryElements = doc.Root.Elements("category");
foreach(var el in categoryElements.ToList())
{
categoriesElement.Add(new XElement(el));
el.Remove();
}
doc.Element("results").Add(categoriesElement);
//doc.Save(<filepath>);
XElement elem = XElement.Parse(xml);
elem = new XElement("results",
new XElement("root", elem.Element("root").Value),
new XElement("categories", elem.Descendants("category"))
);
Ideally the xml can be transformed using xslt. Basics on xslt transforation can be found below,
http://support.microsoft.com/kb/307322
http://www.w3schools.com/xsl/
Using xslt makes you solution or code more managable. Hope this helps

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