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...
Related
I'm trying to get a single value from an XML using the SelectSingleNode, but it keeps returning null on me.
I've been looking here on SO and it seems it has something to do with the namespace. I tried adding it but I keep getting null.
The XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<EML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xnl="urn:oasis:names:tc:ciq:xnl:4"
xmlns:xal="urn:oasis:names:tc:ciq:xal:4"
xmlns="urn:oasis:names:tc:evs:schema:eml"
xmlns:martine="http://www.martine.be/extensions"
Id="510"
SchemaVersion="7.0"
xsi:schemaLocation="urn:oasis:names:tc:evs:schema:eml schema/510-count-v7-0.xsd
http://www.martine.be/extensions schema/martine-eml-extensions.xsd">
<EMLHeader>
<TransactionId>01</TransactionId>
<ManagingAuthority>
<AuthorityIdentifier>2</AuthorityIdentifier>
<AuthorityName>
<NameElement ElementType="">VLR</NameElement>
</AuthorityName>
<Description>Some Description</Description>
<OrganizationURL>Unknown</OrganizationURL>
<AuthorityAddress/>
</ManagingAuthority>
</EMLHeader>
I'm trying to extract the Description using the code below:
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:evs:schema:eml");
XmlNode testNode = doc.SelectSingleNode("/ns:EML/ns:EMLHeader/ns:ManagingAuthority/ns:Description", nsmgr);
if (testNode != null)
{
Console.WriteLine(testNode.InnerText);
}
What am doing wrong?
Tested this and you are missing closing </EML> tag. This was the error I got
Unhandled Exception: System.Xml.XmlException: Unexpected end of file has occurred. The following elements are not closed: EML. Line 24, position 17.
TestCodeApp.cs
using System;
using System.Xml;
public class Program
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:evs:schema:eml");
XmlNode testNode = doc.SelectSingleNode("/ns:EML/ns:EMLHeader/ns:ManagingAuthority/ns:Description", nsmgr);
if (testNode != null)
{
Console.WriteLine(testNode.InnerText);
}
}
}
input.xml
<?xml version="1.0" encoding="UTF-8"?>
<EML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xnl="urn:oasis:names:tc:ciq:xnl:4"
xmlns:xal="urn:oasis:names:tc:ciq:xal:4"
xmlns="urn:oasis:names:tc:evs:schema:eml"
xmlns:martine="http://www.martine.be/extensions"
Id="510"
SchemaVersion="7.0"
xsi:schemaLocation="urn:oasis:names:tc:evs:schema:eml schema/510-count-v7-0.xsd
http://www.martine.be/extensions schema/martine-eml-extensions.xsd">
<EMLHeader>
<TransactionId>01</TransactionId>
<ManagingAuthority>
<AuthorityIdentifier>2</AuthorityIdentifier>
<AuthorityName>
<NameElement ElementType="">VLR</NameElement>
</AuthorityName>
<Description>Some Description</Description>
<OrganizationURL>Unknown</OrganizationURL>
<AuthorityAddress/>
</ManagingAuthority>
</EMLHeader>
</EML>
Your code look OK, except:
you missed close node in the xml file: ""
if your content is contain information of above xml, then you can use doc.LoadXML(content), otherwise you should use doc.Load(fileName).
Your xml file should be:
<?xml version="1.0" encoding="UTF-8"?>
<EML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xnl="urn:oasis:names:tc:ciq:xnl:4"
xmlns:xal="urn:oasis:names:tc:ciq:xal:4"
xmlns="urn:oasis:names:tc:evs:schema:eml"
xmlns:martine="http://www.martine.be/extensions"
Id="510"
SchemaVersion="7.0"
xsi:schemaLocation="urn:oasis:names:tc:evs:schema:eml schema/510-count-v7-0.xsd
http://www.martine.be/extensions schema/martine-eml-extensions.xsd">
<EMLHeader>
<TransactionId>01</TransactionId>
<ManagingAuthority>
<AuthorityIdentifier>2</AuthorityIdentifier>
<AuthorityName>
<NameElement ElementType="">VLR</NameElement>
</AuthorityName>
<Description>Some Description</Description>
<OrganizationURL>Unknown</OrganizationURL>
<AuthorityAddress/>
</ManagingAuthority>
</EMLHeader>
</EML>
And then you can read it:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:evs:schema:eml");
XmlNode testNode = doc.SelectSingleNode("/ns:EML/ns:EMLHeader/ns:ManagingAuthority/ns:Description", nsmgr);
if (testNode != null)
{
Console.WriteLine(testNode.InnerText);
}
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");
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.
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();
Is there anyway I can create nodes out of a string? I've searched the Web looking for something, but couldn't find anything that works!
string _configFileName = #"d:\junk\config.xml";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(_configFileName);
string xmlTags = #"<queue name=queueName autoStart=true>
<deleteFile>true</deleteFile>
<impersonation enabled=true>
<user>domain\username</user>
<password encrypted="true">********</password>
</impersonation>
<tasks>
<task>cp</task>
<task>rm</task>
</tasks>
</queue>";
queueParent.InnerText = str;//the Xml parent node of the new queue node that I want to add
xmldoc.Save();//will write <queue name= INSTEAD OF <queue name=
So the problem is having the special characters in XML "<" and ">" written into the file as "<" and ">".
Your input is much appreciated, thanks.
I think you want the InnerXml property instead of InnerText.
For example:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
doc.AppendChild(root);
root.InnerXml = "<child>Hi!</child>";
doc.Save(Console.Out);
}
}
You can create an XmlDocument from a string using xmldoc.LoadXml(xmlTags)