I want to create a simple XML file to store some settings that can be easily changed in a text editor. This is my XML file:
<connection>
<hostname>the.host.name</hostname>
<port>1000</port>
<database>theDbName</database>
</connection>
I am trying to use Linq to XML now to read that info into my program, but it gives me an error:
Could not find an implementation of the query pattern for source type 'System.Xml.Linq.XElement'. 'Select' not found.
My code is as follows:
XElement root = XElement.Load(".\\Resources\\Connection.xml");
string host = from el in root.Element("hostname") select el.Element("text");
XDocument xDoc = XDocument.Load(".\\Resources\\Connection.xml");
string host = (string)xDoc.Root.Element("hostname");
I think you're confused on how your XML structure should look and the way you read that XML with LinQ. First of all place your connection-element in a root called connections. Your XML looks like this now:
<?xml version="1.0" encoding="utf-8"?>
<connections>
<connection>
<hostname>the.host.name</hostname>
<port>1000</port>
<database>theDbName</database>
</connection>
</connections>
Now you can select the elements under that root and read all the data from it. Example code looks like following:
var root = XElement.Load(".\\Resources\\Connection.xml");
var connection = root.Elements("connection").FirstOrDefault();
if(connection != null)
{
var host = connection.Element("hostname").Value;
//do something with 'host'
}
Update:
If you don't want a root element 'connections', you can omit it and use following code to read the XML:
var xmlDoc = XDocument.Load("G:\\Connection.xml");
var connection = xmlDoc.Descendants("connection").FirstOrDefault();
if(connection != null)
{
var host = connection.Element("hostname").Value;
//do something with 'host'
}
Related
I need to validate the contents of an existing config file.
It looks like this:
<configuration>
<appSettings>
<Version>HB.2017.0</Version>
<FORMAT_VERSION>2.4</FORMAT_VERSION>
<MISC>Stuff.2014.0</MISC>
</appSettings>
</configuration>
I've been trying to write something in C# to read the file and assign the content of the Version and Format-Version and then validates if it is true or not but I keep getting a null pointer error.
Here's what I have so far:
public void ValidateConfigVersionSetting()
{
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\project.exe.config");
XmlNode node = doc.DocumentElement.SelectSingleNode("/Version");
string nodeContent = node.InnerText;
if (nodeContent.Equals("2017.0"))
{
Report.Success("Config", "Config is correct! 2017.");
}
else
{
Report.Failure("Config", "Config is not 2017.");
}
}
This is a code module for a Ranorex automation suite so the Validate.IsTrue comes from that. Is the way I store the innertext correct?
If that code is exactly as written, then you have a mistake here:
Validate.IsTrue(nodeContent="HB.2017.0", "Config is proper");
You're assigning the string to nodeContent, not comparing it.
I am new to WPF and am attempting to write a child node to an XML file. Here is the file...
<?xml version="1.0" encoding="utf-8"?>
<Sequences>
<LastSavedSequence name="Last Saved Sequence">
<Test name="Measure Battery Current(Stim)" testNumber="5" Vbat="3.7" Frequency="20" PulseWidth="500" Amplitude="1" Resistance="1600" Anode="1" Cathode="2" ActiveDischarge=""/>
<Test name="Measure Batther Current(No Stim)" testNumber="6" Vbat="2.9" Frequency="20" PulseWidth="500" Amplitude="1" Resistance="1600" Anode="1" Cathode="2" ActiveDischarge=""/>
</LastSavedSequence>
<ScottTestSequence name="Scott Test Sequence">
<Test name="VMO Status" testNumber="4" Vbat="3.7" Frequency="20" PulseWidth="1000" Amplitude="6" Resistance="3000" Anode="1" Cathode="2" ActiveDischarge=""/>
<Test name="Measure Battery Current(Stim)" testNumber="5" Vbat="3.7" Frequency="20" PulseWidth="500" Amplitude="1" Resistance="1600" Anode="1" Cathode="2" ActiveDischarge=""/>
<Test name="Measure Batther Current(No Stim)" testNumber="6" Vbat="2.9" Frequency="20" PulseWidth="500" Amplitude="1" Resistance="1600" Anode="1" Cathode="2" ActiveDischarge=""/>
</ScottTestSequence>
</Sequences>
I am attempting to create an XML child block to go within . I used stringBuilder and then am trying to do an attach child and then a .save. XMLData2 is a global list and contains a the child elements that I get in the for each. Here is my code...
public static List<System.Xml.XmlNode> xmlData2 = new List<System.Xml.XmlNode>();
XmlDocument xmlFromOutSideSequenceFile = new XmlDocument();
xmlFromOutSideSequenceFile.Load("c:\\Users/StarkS02/Documents/SavedSequenceFile.xml");
StringBuilder exampleNode = new StringBuilder();
exampleNode.Append("<");
exampleNode.Append(tbSequenceName.Text.ToString().Replace(" ", ""));
exampleNode.Append(" name=");
exampleNode.Append("'");
exampleNode.Append(tbSequenceName.Text);
exampleNode.Append("'");
exampleNode.Append(">");
foreach (XmlNode node in xmlData2)
{
XmlElement child = xmlFromOutSideSequenceFile.CreateElement(string.Empty, node.OuterXml, string.Empty);
exampleNode.Append("</");
exampleNode.Append(tbSequenceName.Text.ToString().Replace(" ", ""));
exampleNode.Append(">");
xmlFromOutSideSequenceFile.AppendChild(exampleNode);
xmlFromOutSideSequenceFile.Save("c:\\Users/StarkS02/Documents/SavedSequenceFile.xml");
I get a compiler error on the .appendChild statement that I cannot convert a stringBuilder to an XML node. This makes sense but I'm not sure how to fix it. Any ideas?
You can create an XML fragment and append to the document.
var xmlFromOutSideSequenceFile = new XmlDocument();
xmlFromOutSideSequenceFile.Load("c:\\Users/StarkS02/Documents/SavedSequenceFile.xml");
See here for more on DocumentFragment
https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createdocumentfragment(v=vs.110).aspx
var fragment = xmlFromOutSideSequenceFile.CreateDocumentFragment();
fragment.InnerXml = #"<somexml></somexml>";
xmlFromOutSideSequenceFile.DocumentElement.FirstChild.AppendChild(fragment);
See here for more on XMLNode
https://msdn.microsoft.com/en-us/library/system.xml.xmlnode(v=vs.110).aspx
Decide where you want to put it.
.FirstChild
.LastChild
.NextSibling
.ParentNode
.PreviousSibling
Hope this helps! Cheers!
I'm writing a configuration storage method for one of my clients and they requested that it be in XML. I've managed to get it to work other than one issue; the first element is missing. My XML file is:
<?xml version="1.0" encoding="utf-8" ?>
<config>
<username>test</username>
<password>pass</password>
<autologin>true</autologin>
</config>
My Parsing command is:
void parseConfigFile()
{
while (configstr.Read())
{
if (configstr.IsStartElement())
{
config.Add(configstr.Name,configstr.ReadString());
}
}
}
and the result (configstr) is:
autologin = true
config =
password = pass
var document = XDocument.Load("file.xml");
var config = document.Root;
var userName = (string)config.Element("username");
var password = (string)config.Element("password");
var autologin = (bool)config.Element("autologin");
I made a request to a third party API and it gives me the following response in XML.
<?xml version="1.0" ?>
<abc>
<xyz>
<code>-112</code>
<message>No such device</message>
</xyz>
</abc>
I read this using this code.
XmlDocument doc = new XmlDocument();
doc.Load("*** url ***");
XmlNode node = doc.SelectSingleNode("/abc/xyz");
string code = node.SelectSingleNode("code").InnerText;
string msg = node.SelectSingleNode("message").InnerText;
Response.Write("Code: " + code);
Response.Write("Message: "+ msg);
But I get an error on this line:
string code = node.SelectSingleNode("code").InnerText;
Error is:
Object reference not set to an instance of an object.
I changed the first line of your XML file into:
<?xml version="1.0"?>
to make it valid XML. With this change, your code works for me. Without the change, the parser throws an exception.
You can use LINQ to XML (if confortable):
XDocument doc = XDocument.Load(url);
var selectors = (from elements in doc.Elements("abc").Elements("xyz")
select elements).FirstOrDefault();
string code = selectors.Element("code").Value;
string msg = selectors.Element("message").Value;
As you've given it, there doesn't seem to be anything wrong with your code Edit : Your declaration is wrong, as svinja pointed out, and your xml won't even load into the XmlDocument.
However, I'm guessing that your xml is more complicated, and there is at least one namespace involved, which would cause the select to fail.
It isn't pretty, but what you can do is use namespace agnostic xpath to locate your nodes to avoid using a XmlNamespaceManager:
XmlDocument doc = new XmlDocument();
doc.Load("*** url ***");
XmlNode node = doc.SelectSingleNode("/*[local-name()='abc']/*[local-name()='xyz']");
string code = node.SelectSingleNode("*[local-name()='code']").InnerText;
string msg = node.SelectSingleNode("*[local-name()='message']").InnerText;
Response.Write("Code: " + code);
Response.Write("Message: "+ msg);
Edit - Elaboration
Your code works fine if you correct the declaration to <?xml version="1.0"?>
However, if you introduce namespaces into the mix, your code will fail unless you use namespace managers appropriately.
My agnostic xpath above will also parse an xml document like so:
<?xml version="1.0"?>
<abc xmlns="foo">
<xyz xmlns="bar">
<code xmlns="bas">-112</code>
<message xmlns="xyz">No such device</message>
</xyz>
</abc>
<?xml version="1.0">
<abc>
<xyz>
<code>-112</code>
<message> No such device </message>
</xyz>
</abc>
try to set a list:
XmlNodeList nodeList = root.SelectNodes("/abc/xyz");
then read all the nodes and get their text:
foreach(XmlNode node in nodeList)
{
if(node.Name == "code")
{
string code = node.InnerText;
}
else
if(node.Name == "message")
{
string msg = node.InnerText;
}
}
[XmlRoot("abc")]
public class Entity
{
[XmlElement("xyz")]
public SubEntity SubEntity { get; set; }
}
public class SubEntity
{
[XmlElement("code")]
public string Code { get; set; }
[XmlElement("message")]
public string Message { get; set; }
}
And use standart xmlserializer
var xmlSerializer = new XmlSerializer(typeof(Entity));
var result = xmlSerializer.Deserialize(new XmlTextReader("*** url ***"));
Response.Write("Code: " + result.SubEntity.Code);
Response.Write("Message: "+ result.SubEntity.Message);
I am trying to read an XML feed to get the last post date. My xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>
<channel>
<title>mysite</title>
<atom:link href="http://www.mysite.com/news/feed/" rel="self" type="application/rss+xml" />
<link>http://www.mysite.com/news</link>
<description>mysite</description>
<lastBuildDate>Tue, 22 Nov 2011 16:10:27 +0000</lastBuildDate>
<language>en</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>http://wordpress.org/?v=3.0.4</generator>
<item>
<title>My first post!</title>
<link>http://www.mysite.com/news/2011/11/22/docstore-v2-released/</link>
<comments>http://www.mysite.com/news/2011/11/22/docstore-v2-released/#comments</comments>
<pubDate>Tue, 22 Nov 2011 16:10:27 +0000</pubDate>
<dc:creator>mysite</dc:creator>
<category><![CDATA[News]]></category>
<category><![CDATA[Promotions]]></category>
<category><![CDATA[docstore]]></category>
I didn't show all of the xml since it is rather long.
My method, so far, looks like this:
private void button1_Click(object sender, EventArgs e)
{
var XmlDoc = new XmlDocument();
// setup the XML namespace manager
var mgr = new XmlNamespaceManager(XmlDoc.NameTable);
// add the relevant namespaces to the XML namespace manager
mgr.AddNamespace("ns", "http://purl.org/rss/1.0/modules/content/");
var webClient = new WebClient();
var stream = new MemoryStream(webClient.DownloadData("http://www.mysite.com/news/feed/"));
XmlDoc.Load(stream);
// **USE** the XML anemspace in your XPath !!
XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response");
while (NodePath != null)
{
foreach (XmlNode Xml_Node in NodePath)
{
Console.WriteLine(Xml_Node.Name + ": " + Xml_Node.InnerText);
}
}
}
I'm having a problem with it telling me:
Namespace Manager or XsltContext needed. This query has a prefix,
variable, or user-defined function.
All I want to pull out of this xml code is the 'lastBuildDate'. I'm going in circles trying to get this code right.
Can someone tell me what I am doing wrong here?
Thank you!
You're not using the namespace manager.
// **USE** the XML anemspace in your XPath !!
XmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/ns:Response", mgr);
There is only one of the element you are going after, you could go directly to it using the XPath. That element is also in the default namespace, so you do not need to do anything special to get to it. What about:
var XPATH_BUILD_DATE="/rss/channel/lastBuildDate";
private void button1_Click(object sender, EventArgs e){
var xmlDoc = new XmlDocument();
var webClient = new WebClient();
var stream = new MemoryStream(webClient.DownloadData("http://www.mysite.com/news/feed/"));
xmlDoc.Load(stream);
XmlElement xmlNode = (XmlElement)xmlDoc.SelectSingleNode(XPATH_BUILD_DATE);
Console.WriteLine(xmlNode.Name + ": " + xmlNode.InnerText);
}
If you did however need to dig into elements in a different namespace, you can do that also with the XPath (example, getting the dc:creator:
/rss/channel/item[1]/*[local-name() = 'creator']