I am very new to C#, but it seems as though this should be pretty straight forward. I am trying to parse an XML string returned from a web feed that looks like this:
<autnresponse xmlns:autn="http://schemas.autonomy.com/aci/">
<action>QUERY</action>
<response>SUCCESS</response>
<responsedata>
<autn:numhits>6</autn:numhits>
<autn:hit>
<autn:reference>http://something.what.com/index.php?title=DPM</autn:reference>
<autn:id>548166</autn:id>
<autn:section>0</autn:section>
<autn:weight>87.44</autn:weight>
<autn:links>Castlmania,POUCH</autn:links>
<autn:database>Postgres</autn:database>
<autn:title>A Pouch and Mail - Castlmania</autn:title>
<autn:content>
<DOCUMENT>
<DRETITLE>Castlmania Pouch and Mail - Castlmania</DRETITLE>
<DRECONTENT>A paragraph of sorts that would contain content</DRECONTENT>
</DOCUMENT>
</autn:content>
</autn:hit>
<autn:hit>...</autn:hit>
<autn:hit>...</autn:hit>
<autn:hit>...</autn:hit>
<autn:hit>...</autn:hit>
</autnresponse>
with no luck.
I am using this code to start:
XmlDocument xmlString = new XmlDocument();
xmlString.LoadXml(xmlUrl);
XmlElement root = xmlString.DocumentElement;
XmlNode GeneralInformationNode =
root.SelectSingleNode("//autnresponse/responsedata/autn:hit");
foreach (XmlNode node in GeneralInformationNode)
{
Console.Write("reference: "+node["autn:reference"]+" Title:"+node["DRETITLE"]+"<br />);
}
And I would like to print the DRETITLE and autn:reference element of within each of the autn:hit elements. Is that even doable with my approach?
I have tried looking and several example on the good old web like this to no avail.
The error that comes back is:
System.Xml.XPath.XpathEception {NameSpace Manager or XsltContext
needed. ...}
Thanks in advance.
UPDATE:
In trying to use XmlNamespaceManager, one has to give it a url to the schema definition like so:
XmlNamespaceManager namespmng = new XmlNamespaceManager (xmlString.NameTable);
namespmng.AddNamespace("autn","http://someURL.com/XMLschema");
The problem seems to be that now the error is gone, but the data is not displaying. I should mention that I am working off of a machine that does not have internet connectivity. The other thing is the schema seems to be unavailable. I am guessing that XmlNamespaceManager would work once able to connect to the internet right?
Using System.Xml.Linq it could be something like this:
var doc = XElement.Load(xmlUrl);
var ns = doc.GetNamespaceOfPrefix("autn");
foreach (var hit in doc.Descendants(ns + "hit"))
{
var reference = hit.Element(ns + "reference").Value;
var dretitle = hit.Descendants("DRETITLE").Single().Value;
WriteLine($"ref: {reference} title: {dretitle}");
}
Firstly, the exception you're getting is because you haven't loaded the namespace using the XmlNamespaceManager for the xml you're parsing. Something like this:
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlString.NameTable);
if (root.Attributes["xmlns:autn"] != null)
{
uri = root.Attributes["xmlns:autn"].Value;
namespaceManager.AddNamespace("autn", uri);
}
Secondly, what you're trying to do is possible. I'd suggest using root.SelectNodes(<your xpath here>) which will return a collection of autn:hit nodes that you can loop through instead of SelectSingleNode which will return one node. Within that you can drill down to the content/DOCUMENT/DRETITLE and pull the text for the DRETITLE node using either XmlNode.Value if you select the text specifically or XmlNode.InnerText on the DRETITLE node.
Related
I have my XML as
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<recordsDirectory>F:/model_RCCMREC/</recordsDirectory>
<transferDirectory>F:/model_RCCMrecTransfered/</transferDirectory>
<logDirectory>F:/model_RCCMLOG/</logDirectory>
<connectionstring>Data Source=192.168.1.7;Initial Catalog=RCCMdb;User ID=genesys;Password=genesys</connectionstring>
<table>RCCMrec</table>
<DBdestination>
<val1>ANI</val1>
<val2>DNIS</val2>
<val3>Date</val3>
<val4>Time</val4>
<val5>ConnId</val5>
<val6>UUID</val6>
<val7>EmployeeId</val7>
<val8>AgentDN</val8>
</DBdestination>
</configuration>
I need the value of the recordsDirectory tag.
I tried this,
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("recordsDirectory").InnerText.ToString();
But got an error saying
Object reference not set to an instance of an object.
Yes, SelectSingleNode("recordsDirectory") will return null, because you're applying that XPath to the document itself - which doesn't have a recordsDirectory element at the top level, it has a configuration element. You want:
xmldoc.SelectSingleNode("configuration/recordsDirectory")
Or go via the root element:
xmldoc.DocumentElement.SelectSingleNode("recordsDirectory")
(Or you can fetch all descendant elements call recordsDirectory, etc. There are plenty of options here.)
Personally I'd suggest changing to use LINQ to XML if you can, as it's a simpler way of using XML, IMO. It's not too bad in the code you've given so far, but as you do more things with XmlDocument you'll run into it being a bit of a pain - relatively speaking, anyway.
You should also consider separating the "fetching the node" from getting the text, so you can validate that you've found the one you want:
XmlNode node = xmldoc.DocumentElement.SelectSingleNode("recordsDirectory");
if (node != null)
{
// Use it
}
else
{
// No such node. What do you want to do?
}
Try this one in your SelectSingleNode
XmlNode node = doc.SelectSingleNode("/configuration/recordsDirectory");
string s = node.InnerText.ToString();
Hi To read the recordsDirectory tag you need to do :
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("C:/Users/yachna/Desktop/RCCM_TOOL/configRCCM.xml");
string bvalue = xmldoc.SelectSingleNode("configuration/recordsDirectory").InnerText.ToString();
It will work perfactly
I am simply trying to read a particular node from an XML and use it as a string variable in a condition. This gets me to the XML file and gives me the whole thing.
string url = #"http://agent.mtconnect.org/current";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);
richTextBox1.Text = xmlDoc.InnerXml;
But I need the power state "ON" of "OFF" (XML section below, can view the whole XML online)
<Events><PowerState dataItemId="p2" timestamp="2013-03-11T12:27:30.275747" name="power" sequence="4042868976">ON</PowerState></Events>
I have tried everything I know of. I am just not that familiar with XML files. and the other posts get me nowhere.
HELP PLEASE!
You may try LINQ2XML for that:
string value = (string) (XElement.Load("http://agent.mtconnect.org/current")
.Descendants().FirstOrDefault(d => d.Name.LocalName == "PowerState"))
If you wanted to avoid LINQ, or if it is not working for you you can use straight XML traversal for this:
string url = #"http://agent.mtconnect.org/current";
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(url);
System.Xml.XmlNamespaceManager theNameManager = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
theNameManager.AddNamespace("mtS", "urn:mtconnect.org:MTConnectStreams:1.2");
theNameManager.AddNamespace("m", "urn:mtconnect.org:MTConnectStreams:1.2");
theNameManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
System.Xml.XmlElement DeviceStreams = (System.Xml.XmlElement)xmlDoc.SelectSingleNode("descendant::mtS:DeviceStream", theNameManager);
System.Xml.XmlNodeList theStreams = DeviceStreams.SelectNodes("descendant::mtS:ComponentStream", theNameManager);
foreach (System.Xml.XmlNode CompStream in theStreams)
{
if (CompStream.Attributes["component"].Value == "Electric")
{
System.Xml.XmlElement EventElement = (System.Xml.XmlElement)CompStream.SelectSingleNode("descendant::mtS:Events", theNameManager);
System.Xml.XmlElement PowerElement = (System.Xml.XmlElement)EventElement.SelectSingleNode("descendant::mtS:PowerState", theNameManager);
Console.Out.WriteLine(PowerElement.InnerText);
Console.In.Read();
}
}
When traversing any document with a default namespace in the root node, I have found it is imperative to have a namespace manager. Without it the document is just un-navigable.
I created this code in a console application. It worked for me. Also I am no guru and I may be making some mistakes here. I am not sure if there is some way to have the default namespace referenced without naming it (mtS). Anyone who knows how to make this cleaner or more efficient please comment.
EDIT:
For one less level of 'clunk' you can change this:
if (CompStream.Attributes["component"].Value == "Electric")
{
Console.Out.WriteLine(((System.Xml.XmlElement)CompStream.SelectSingleNode("descendant::mtS:Events", theNameManager)).InnerText;);
Console.In.Read();
}
because there is only one element in there and its innerText is all you will get.
I'm a completly New to Linq2XML as I code to much lines to perform simple things, and in a simple project I wanted to give it a try...
I'm with this for 2 hours and nothing I do get's it right :(
I'm really, really thinking to go back to XmlNode-code-alike
The Task:
I send a SOAP Action to an ASMX service and I get the response as XML
I Parse the XML into a XDocument object
I try to get a list of nodes ... err! Problem!
as you can see from this screenshot
alt text http://www.balexandre.com/temp/2010-02-26_0038.png
my XDocument has a Node called TransactionInformationType witch is a Sequence, and I simple want to get all and retrieve the only 2 variables that I need (you can see the code commented) just below select c;
in the Watch window you can see that
doc.Descendants("TransactionInformationType")
returns nothing at all, and seeing by the content of the XDocument in the Text Visualizer, it does exist!
Anyone care to explain and help me passing this HUGE wall?
Thank you!
Added
XDocument content
Answer
the Response XML has
<gettransactionlistResponse xmlns="https://ssl.ditonlinebetalingssystem.dk/remote/payment">
and I must use this as Namespace!
turns out that, to retrieve values, I do need to use the XNamespace as well, so the final code looks like this:
// Parse XML
XDocument doc = XDocument.Parse(strResponse);
XNamespace ns = "https://ssl.ditonlinebetalingssystem.dk/remote/payment";
var trans = from item in doc.Descendants(ns + "TransactionInformationType")
select new TransactionInformationType
{
capturedamount = Convert.ToInt32(item.Element(ns + "capturedamount").Value),
orderid = item.Element(ns + "cardtypeid").Value
};
Thank you all for the help!
var result = doc.Descendants("TransactionInformationType");
selects all descendants in the XDocument that have element name "TransactionInformationType" and are in the empty namespace.
From you screenshot it seems the element you're trying to select is in the namespace "https://ssl.ditonlinebetalingssystem.dk/remote/payment" though.
You need to specify that explicitly:
XNamespace ns = "https://ssl.ditonlinebetalingssystem.dk/remote/payment";
↑↑ ↑
var result = doc.Descendants(ns + "TransactionInformationType");
This should solve you isssue (replace the namespace with the right URL):
XNamespace ns = "https://ssl.ditonline...";
doc.Descendants(ns + "TransactionInformationType");
I have looked around and have not been able to implement a solutions for what I need. I apologize if this seems like a repeat questions.
I'm querying an IDOL service and need to load an object with from the xml response.
Give the sample xml:
<autnresponse xslns:autn="http://schemas.autonomy.com/aci/">
<action>QUERY</action>
<response>SUCCESS</response>
<responsedata>
<autn:numhits>2</autn:numhits>
<autn:totalhits>2</autn:totalhits>
<autn:totaldbdocs>2</autn:totaldbdocs>
<autn:totaldbsecs>2</autn:totaldbsecs>
<autn:hit>
<autn:reference>http://blah</autn:reference>
<autn:title>my title</autn:title>
</autn:hit>
<autn:hit>
<autn:reference>http://blah</autn:reference>
<autn:title>my title</autn:title>
</autn:hit>
</responsedata>
</autnresponse>
I'm trying to load a list of a custom object with linq to XML.
Here is what I have tried as code, and I'm always getting no results.
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("autn", "http://schemas.autonomy.com/aci/");
... Load Xelemet.....
IEnumerable<XElement> urls = raw.Elements(IDOLModule.GetNamespace()+ "hit");
foreach (var single in urls)
{
var t = new url();
t.Title="";
t.Url="";
listURL.Add(t);
}
The urls variable is always coming back empty. I just need to target the autn:hits nodes and load their data to the object.
Cheers,
You could try something like that:
XElement doc = XElement.Parse(#"<autnresponse xmlns:autn=""http://schemas.autonomy.com/aci/"">
<action>QUERY</action>
<response>SUCCESS</response>
<responsedata>
<autn:numhits>2</autn:numhits>
<autn:totalhits>2</autn:totalhits>
<autn:totaldbdocs>2</autn:totaldbdocs>
<autn:totaldbsecs>2</autn:totaldbsecs>
<autn:hit>
<autn:reference>http://blah</autn:reference>
<autn:title>my title</autn:title>
</autn:hit>
<autn:hit>
<autn:reference>http://blah</autn:reference>
<autn:title>my title</autn:title>
</autn:hit>
</responsedata>
</autnresponse>");
XNamespace ns = ("http://schemas.autonomy.com/aci/");
//Console.WriteLine(doc.Descendants(ns + "numhits").First().Value);
IEnumerable<XElement> hits=doc.Descendants(ns + "hit");
foreach (XElement h in hits){
Console.WriteLine(String.Format("{0} - {1}",h.Name.ToString(),h.Elements().First().Value));
};
simple question but I've been dinking around with it for an hour and it's really starting to frustrate me. I have XML that looks like this:
<TimelineInfo>
<PreTrialEd>Not Started</PreTrialEd>
<Ambassador>Problem</Ambassador>
<PsychEval>Completed</PsychEval>
</TimelineInfo>
And all I want to do is use C# to get the string stored between <Ambassador> and </Ambassador>.
So far I have:
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNode x = doc.SelectSingleNode("/TimelineInfo/Ambassador");
which selects the note just fine, now how in the world do I get the content in there?
May I suggest having a look at LINQ-to-XML (System.Xml.Linq)?
var doc = XDocument.Load("C:\\test.xml");
string result = (string)doc.Root.Element("Ambassador");
LINQ-to-XML is much more friendly than the Xml* classes (System.Xml).
Otherwise you should be able to get the value of the element by retrieving the InnerText property.
string result = x.InnerText;
The InnerText property should work fine for you.
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.innertext.aspx
FWIW, you might consider switching API to linq-to-xml (XElement and friends) as IMHO it's a friendly, easier API to interact with.
System.Xml version (NOTE: no casting to XmlElement needed)
var xml = #"<TimelineInfo>
<PreTrialEd>Not Started</PreTrialEd>
<Ambassador>Problem</Ambassador>
<PsychEval>Completed</PsychEval>
</TimelineInfo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.SelectSingleNode("/TimelineInfo/Ambassador");
Console.WriteLine(node.InnerText);
linq-to-xml version:
var xml = #"<TimelineInfo>
<PreTrialEd>Not Started</PreTrialEd>
<Ambassador>Problem</Ambassador>
<PsychEval>Completed</PsychEval>
</TimelineInfo>";
var root = XElement.Parse(xml);
string ambassador = (string)root.Element("Ambassador");
Console.WriteLine(ambassador);
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNode x = doc.SelectSingleNode("/TimelineInfo/Ambassador");
x.InnerText will return the contents
Try using Linq to XML - it provides a very easy way to query xml datasources - http://msdn.microsoft.com/en-us/library/bb387098%28v=VS.100%29.aspx