Read youtube channel xml file with c# xmldocument - c#

I want to get the channel information and list of files from the rss feed for a channel. For instance,
http://gdata.youtube.com/feeds/api/users/google/uploads
is the rss feed for google. How would I get the title for the feed, for instance? Or the list of videos? I tried
WebClient wc = new WebClient();
XmlDocument xd = new XmlDocument();
xd.LoadXml(wc.DownloadString(strUrl));
XmlNode xn = xd.SelectSingleNode("/feed/title");
But xn is always returning null. I also tried "/title", "feed/title", and "title", none of which worked. Similarly for the list of videos, I tired
XmlNodeList vids = xd.SelectNodes("/entry");
And a few other permutations without success.
(Edit adding the xml info so no one will have to click on the link)
Here's what the top of the xml file looks like:
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<id>http://gdata.youtube.com/feeds/api/users/google/uploads</id>
<updated>2013-08-19T21:47:34.674Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://gdata.youtube.com/schemas/2007#video" />
<title type="text">Uploads by Google</title>
<logo>http://www.gstatic.com/youtube/img/logo.png</logo>
</feed>
I just want to know how to get a value out of there, such as the title or the id

Try this:
XmlDocument xml = new XmlDocument();
xml.LoadXml(wc.DownloadString(strUrl));
XmlNodeList xnList = xml.SelectNodes("/Feed/Title");
foreach (XmlNode xn in xnList)
{
string Title= xn["Title"].InnerText;
}
OR
var doc = XDocument.Load(wc.DownloadString(strUrl));
string result = (string)doc.Root.Element("Title");

Related

How to working with xml nodes

I have program with response from website in the xml format with namespace.
example program:
string responsedata;//response data from website
//Creat new XMLdoc object for response data
XmlDocument ResponseDataXml = new XmlDocument();
ResponseDataXml.InnerXml= responsedata;
XmlNamespaceManager xnsm = new XmlNamespaceManager(ResponseDataXml.NameTable);
xnsm.AddNamespace("ps","http://example.com/namespace/ps");
//create xml document fro validating DTD
XmlDocument ValidateXml = new XmlDocument();
//select Nodes <ps:results> ... <result>
XmlNodeList NodesResults = ResponseDataXml.SelectNodes("ps:results/result");
foreach (XmlNode node in NodesResults)
{
ValidateXml.InnerText= "";
ValidateXml.InnerText += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
ValidateXml.InnerText += "<!DOCTYPE SouborN1A SYSTEM \"validate_dtd.dtd\">";
ValidateXml.InnerText+=node.InnerXml;
ValidateXml.Save("validate_temp.xml");
if (validate("validate_temp.xml"))//validate() return true if document is valid
{
Console.WriteLine("Result:" + node.Attributes["id"] + " is valid !!!!!");
// here i can append "result" node in new xml document "Valid_result.xml"
}
else
{
Console.WriteLine("Result:"+ node.Attributes["id"] + "i invalid !!!!!");
// here i can append "result" in new xml document invalid result in to "invalid_result.xml"
}
}
Input postdata:
<ps:report xmlns:ps="example.com.....">
<results xmlns:ps="example.com....." ps:Identifikation="999999">
<result id="11125">
.......
</result>
<result id="1100">
.......
</result>
<result id="111999055">
.......
</result>
<result id="100000">
.......
</result>
</results>
</ps:report>
Please help me... :)
I do not know how to proceed, and work with a given output,
I need mainly validate the item separately and then store in a xml file.
I apologize for my English.
Thanks.
Unfortunately, this question is fairly broad, but generally speaking everything can be done with XML libraries in C#. For example, use the XmlDocument class to create elements and then simply append those elements to the existing nodes.
class Program
{
static void Main(string[] args)
{
var output = new XmlDocument();
output.AppendChild(output.CreateXmlDeclaration("1.0", "utf-8", null));
var xmlns = new XmlNamespaceManager(output.NameTable);
var root = output.CreateElement("ps", "report", "http://example.com/namespace/ps");
var list = output.CreateElement("ps", "results", "http://example.com/namespace/ps");
list.Attributes.Append(output.CreateAttribute("Identifikation"));
list.Attributes[0].Value = "999999";
root.AppendChild(list);
var item = output.CreateElement("ps", "result", "http://example.com/namespace/ps");
item.Attributes.Append(output.CreateAttribute("id"));
item.Attributes[0].Value = "11125";
list.AppendChild(item);
//TODO: Append more validation messages.
output.AppendChild(root);
output.WriteTo(new XmlTextWriter(Console.Out));
System.Console.ReadLine();
}
}
Produces a document like this:
<?xml version="1.0" encoding="utf-8"?>
<ps:report xmlns:ps="http://example.com/namespace/ps">
<ps:results Identifikation="999999">
<ps:result id="11125" />
</ps:results>
</ps:report>

Complicated XML with namespace for beginner

I received an XML file from a client, and I have to reproduce it using C#.
I started today reading about XML files and I'm going anywhere :/
I'm using XMLDocument cause I read it was helpful and not so complicated.
Maybe you can help me guys to understand how to I get exprsions like: to come as a root element.
<DeviceDescription>
<Types namespace="localTypes"/>
<Strings namespace="Unit">
<Language lang="de-DE"/>
<Language lang="en-EN"/>
</Strings>
<Strings namespace="localStrings_child_-1_1">
<Language lang="de-DE">
<String identifier="50">Drehmoment</String>
</Language>
<Language lang="en-EN">
<String identifier="50">Torque</String>
</Language>
</Strings>
<Files namespace="localFiles">
<Language lang="en">
<File fileref="local" identifier="NUM_ICO">
<LocalFile>Motor.ico</LocalFile>
</File>
</Language>
</Files>
part of my code:
//Declaration of the XML Document
XmlDocument doc = new XmlDocument();
XmlNode declaration = doc.CreateXmlDeclaration("1.0", "UNICODE", null);
doc.AppendChild(declaration);
//Name of the Root
XmlNode rootNode = doc.CreateElement("DeviceDescription");
doc.AppendChild(rootNode);
//First Node "Types"
XmlNode typesNode = doc.CreateElement("Types");
XmlAttribute typesAttribute = doc.CreateAttribute("namespace");
typesAttribute.Value = "localTypes";
typesNode.Attributes.Append(typesAttribute);
rootelement.AppendChild(typesNode);
//Second Node "Strings"
XmlNode strings1Node = doc.CreateElement("Strings");
XmlAttribute strings1Attribute = doc.CreateAttribute("namespace");
strings1Attribute.Value = "Unit";
strings1Node.Attributes.Append(strings1Attribute);
rootelement.AppendChild(strings1Node);
//Third Node "Strings"
XmlNode stringsNode2 = doc.CreateElement("Strings");
...
//Third Node "Files"
XmlNode priceNode = doc.CreateElement("Files");
...
I know it's everything wrong cause I can't compile it, maybe someone can help me. Thanks!
You could run this code to generate the items you want and see the output that is built into the console:
XmlDocument doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UNICODE", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
Code to generate the root element...
XmlElement rootelement = doc.CreateElement(string.Empty,
"DeviceDescription", string.Empty);
doc.AppendChild(rootelement);
XmlNode typesNode = doc.CreateElement("Types");
XmlAttribute typesAttribute = doc.CreateAttribute("namespace");
typesAttribute.Value = "localTypes";
typesNode.Attributes.Append(typesAttribute);
rootelement.AppendChild(typesNode);
Code to display the string formed...
Console.WriteLine(doc.OuterXml);
Console.WriteLine("Press any key to exit...");
Console.Read();
Console output:
<?xml version="1.0" encoding="UNICODE"?><DeviceDescription><Types namespace="loc
alTypes" /></DeviceDescription>
Press any key to exit...

XMLNodeList not populating

This is my XML,It is actually an InfoPath form with a word doc attachment in the Attachment node - but I have removed the code for better readablity.
<?xml version="1.0" encoding="UTF-8"?><?mso-infoPathSolution solutionVersion="1.0.0.527" productVersion="14.0.0" PIVersion="1.0.0.0" href="http://intranet/workspace/departments/IT/fakehomepage/Testing/Forms/template.xsn" name="urn:schemas-microsoft-com:office:infopath:Testing:-myXSD-2011-11-22T09-08-23" ?><?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.3"?><?mso-infoPath-file-attachment-present?><my:Template xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapEnc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:tns="http://www.sourcecode.co.za/webservices/RuntimeServices" xmlns:d="http://schemas.microsoft.com/office/infopath/2003/ado/dataFields" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:ns1="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-11-22T09:08:23" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-za">
<my:scn1>
<my:Attachment>the raw source-removed for space saving</my:Attachment>
<my:DataValue>Hello-2013-07-04T09:05:50</my:DataValue>
</my:scn1>
<my:scn2></my:scn2>
<my:scn3></my:scn3>
<my:scn4></my:scn4>
<my:scnSubmit></my:scnSubmit>
<my:scnHideMe></my:scnHideMe>
</my:Template>
This is my attempt so far
XmlDocument myDoc = new XmlDocument(); //works
myDoc.Load(#"Form.xml"); //works
XmlNodeList nl = myDoc.SelectNodes("//Attachment"); //Doesn't work, nodecount still zero.
foreach (XmlNode n in nl)//skips because no nodes loaded.
I have also tried
XmlNodeList nl = myDoc.SelectNodes("//my:scn1");
I need to get the raw source out of there so i can decode and save the word document.
enter code here
To get the namespace working, you need to use XmlNamespaceManager.
XmlDocument myDoc = new XmlDocument();
myDoc.Load(#"Form.xml");
XmlNamespaceManager xmlNsMgr = new XmlNamespaceManager(myDoc.NameTable);
xmlNsMgr.AddNamespace("my", myDoc.DocumentElement.NamespaceURI);
XmlNodeList nl = myDoc.SelectNodes("//my:Attachment", xmlNsMgr);
With this, nl will be populated.

Using Xpath With Default Namespace in C# for Canonicalisation

I'm trying to apply the C14N transform to some generated XML. It appears I can't use LINQ to retrieve the nodes to perform the canonicalisation so I have to go 'old school' with the DOM but I think I'm falling foul of the default namespace.
Here is a sample of my code.
static void Main(string[] args)
{
XmlDocument xDoc = new XmlDocument();
// Load some test xml
string path = #"..\..\TestFiles\Test_1.xml";
if (File.Exists(path) == true)
{
xDoc.PreserveWhitespace = true;
using (FileStream fs = new FileStream(path, FileMode.Open))
{
xDoc.Load(fs);
}
}
//Instantiate an XmlNamespaceManager object.
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xDoc.NameTable);
//Add the namespaces used in books.xml to the XmlNamespaceManager.
xmlnsManager.AddNamespace("", "http://www.myApps.co.uk/");
// Create a list of nodes to have the Canonical treatment
//Execute the XPath query using the SelectNodes method of the XmlDocument.
//Supply the XmlNamespaceManager as the nsmgr parameter.
//The matching nodes will be returned as an XmlNodeList.
XmlNodeList nodeList = xDoc.SelectNodes("/ApplicationsBatch/Applications|/ApplicationsBatch/Applications//*", xmlnsManager);
// Perform the C14N transform on the data
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
transform.LoadInput(nodeList);
MemoryStream ms = (MemoryStream)transform.GetOutput(typeof(Stream));
File.WriteAllBytes(#"..\..\TestFiles\ModifiedTest_1", ms.ToArray());
}
And my XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ApplicationsBatch xmlns="http://www.myApps.co.uk/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<MessageHeader>
<MessageID>00000003</MessageID>
<Body>11223344556</Body>
<Timestamp>2011-08-02T09:00:00</Timestamp>
<MessageCheck>?</MessageCheck>
</MessageHeader>
<Applications>
<Application>
<ApplicantDetails>
<Title>MR</Title>
<Forename>HOMER</Forename>
<Middlenames>
<Middlename></Middlename>
</Middlenames>
<PresentSurname>SIMPSON</PresentSurname>
<CurrentAddress>
<Address>
<AddressLine1>ADDRESS LINE1</AddressLine1>
<AddressLine2>ADDRESS LINE2</AddressLine2>
<AddressTown>ADDRESS Town</AddressTown>
<AddressCounty>COUNTY</AddressCounty>
<Postcode>POST CODE</Postcode>
<CountryCode>GB</CountryCode>
</Address>
<ResidentFromGyearMonth>2007-01</ResidentFromGyearMonth>
</CurrentAddress>
</ApplicantDetails>
</Application>
<Application>
<ApplicantDetails>
<Title>MR</Title>
<Forename>BART</Forename>
<Middlenames>
<Middlename></Middlename>
</Middlenames>
<PresentSurname>SIMPSON</PresentSurname>
<CurrentAddress>
<Address>
<AddressLine1>ADDRESS LINE1</AddressLine1>
<AddressLine2>ADDRESS LINE2</AddressLine2>
<AddressTown>ADDRESS Town</AddressTown>
<AddressCounty>COUNTY</AddressCounty>
<Postcode>POST CODE</Postcode>
<CountryCode>GB</CountryCode>
</Address>
<ResidentFromGyearMonth>2007-01</ResidentFromGyearMonth>
</CurrentAddress>
</ApplicantDetails>
</Application>
</Applications>
</ApplicationsBatch>
I've read a few other topics around the area and came across this Gem but it's not solved the problem.
Using the XPath Visualiser shows the required nodes should be selected but my code fails to select any.
I've found a partial answer to my problem.
When a new namespace is added to the manager it appears that the default namespace can't be an empty string.
This is what I ended up with:
//Instantiate an XmlNamespaceManager object.
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xDoc.NameTable);
//Add the namespaces used to the XmlNamespaceManager.
xmlnsManager.AddNamespace("x", "http://www.myApps.co.uk/");
I then needed to modify the XPath to reflect the namespace identifier like this:
// Create a list of nodes to have the Canonical treatment
//Execute the XPath query using the SelectNodes method of the XmlDocument.
//Supply the XmlNamespaceManager as the nsmgr parameter.
//The matching nodes will be returned as an XmlNodeList.
XmlNodeList nodeList = xDoc.SelectNodes("/x:ApplicationsBatch/x:Applications|/x:ApplicationsBatch/x:Applications//*", xmlnsManager);
The nodes are now selected and ready for transformation... although that returns the correct structure of XML but all the values have been removed but that is a problem for another question.

Tag contents adding to XML file in c# window application

i have an xml file sitemap.xml as shown below ..i need to add one more
tag here after <Name> tag..Means After <Name>test</Name> tag here
i need to add destination tag like <Destination>NY</Destination>
.Can we add contents to xml through a textbox by pressing a button
control without manually doing
this is xml file sitemap.xml
<?xml version="1.0" encoding="utf-8" ?>
<ObjectClass>
<Image>00000000-0000-0000-0000-000000000000</Image>
<Description />
<Name>test</Name>
<DefaultApp>00000000-0000-0000-0000-000000000000</DefaultApp>
<ID>464930eb-e518-4d0c-b80b-184c97c7dd27</ID>
<ParentClassID>00000000-0000-0000-0000-000000000002</ParentClassID>
<DynamicPopulation>false</DynamicPopulation>
<TimeoutPeriod>0</TimeoutPeriod>
<Persist>false</Persist>
<ClassVersion>1</ClassVersion>
<Reinitialize>false</Reinitialize>
</ObjectClass>
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlElement elt = doc.CreateElement("Destination");
elt.InnerText = "NY";
doc.DocumentElement.AppendChild(elt);
doc.Save(fileName);
To delete an element :
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement elt = doc.DocumentElement.SelectSingleNode("Destination") as XmlElement;
if (elt != null)
doc.DocumentElement.RemoveChild(elt);
doc.Save();

Categories