I am trying to obtain the complete string of the query element (2nd element) within an xml string like the following:
"<iq type=\"result\" id=\"Roster\" to=\"JJJ#mail.kkk.com\"><query
xmlns=\"jabber:iq:roster\"><item jid=\"al#abc.def.com\" name=\"Albert\"
subscription=\"both\"><group>A</group></item></query></iq>"
I am using XmlDocument and code that looks like this:
XmlDocument XDoc = new XmlDocument();
XDoc.LoadXml(DataBuf);
XmlElement QueryElem = XDoc.DocumentElement["query"];
string QueryBuf = QueryElem.InnerXml;
I need the full xml string starting with the query element. The InnerXML method only returns the data starting with the "item" data.
How can I obtain the full string starting with query that ends with /query and that does not contain the iq element data?
Use XmlNode.OuterXml property:
string QueryBuf = QueryElem.OuterXml;
returns
<query xmlns="jabber:iq:roster"><item jid="al#abc.def.com" name="Albert" subscription="both"><group>A</group></item></query>
Related
How to get the xml node value in a string.
i am getting This error
Data at the root level is invalid. Line 1, position 1.
error shown in this line
xmldoc.LoadXml(xmlFile);
my xml
<?xml version="1.0" encoding="utf-8" ?>
<UOM>
<!-- The selected currency used will be stored here for Code reference" -->
<ActiveCurrencyType>
<ActiveCurrency>U.S.Dollar</ActiveCurrency>
<ActiveCode>USD</ActiveCode>
<ActiveSymbol>$</ActiveSymbol>
</ActiveCurrencyType>
<!-- The selected Dimension used will be stored here for Code reference -->
<ActiveDimension>
<ActiveDimensionUOM>Inches</ActiveDimensionUOM>
<ActiveDimensionSymbol>.in</ActiveDimensionSymbol>
</ActiveDimension>
<!-- The selected weight used will be stored here for Code reference -->
<ActiveWeight>
<ActiveWeightUOM>Pounds</ActiveWeightUOM>
<ActiveWeightSymbol>lb</ActiveWeightSymbol>
</ActiveWeight>
</UOM>
C# code
string xmlFile = Server.MapPath("~/HCConfig/HCUOM.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlFile);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("ActiveDimensionSymbol");
string ActiveDimensionSymbol = string.Empty;
foreach (XmlNode node in nodeList)
{
ActiveDimensionSymbol = node.InnerText;
}
How can I achieve this?
You're using the wrong overload, LoadXml doesn't do what you think it does.
Use xmldoc.Load(xmFile); because that method takes an file path as input. LoadXml expects an string with xml in it.
The exception is an indicator of that mistake. What is processed is not XML, and a filepath isn't that.
After this changes the string ActiveDimensionSymbol contains .in if I run this locally.
If you want to use LoadXml you should first read your whole file in a string, for example like so:
xmldoc.LoadXml(File.ReadAllText(xmlFile));
but is really only overhead to call File.ReadAllText if there is an method that accepts a file.
You can use the Descendants() method to get all XElements by certain name, found in the System.Xml.Linq namespace.
XDocument doc = XDocument.Load("XMLFile1.xml");
string[] allActiveWeightUOMs = doc.Descendants("ActiveWeightUOM").Select(o => o.Value).ToArray();
// allActiveWeightUOMs : "Pounds" ...
As can seen here link the method that you are using to load the XML excepts xml by string not xml file. You can use XmlDocument.Load instead of XmlDocument.LoadXml
Try this code its works just fine with this xml
string xmlFile = Server.MapPath("~/HCConfig/HCUOM.xml");
XDocument doc = XDocument.Load(xmlFile );
var nodeList = doc.Descendants("ActiveDimensionSymbol");
string ActiveDimensionSymbol = string.Empty;
foreach (var node in nodeList)
{
ActiveDimensionSymbol = node.Value;
}
I have a service which returns the below xml as string.I am using Xdocument parse method and XmlDocument load methods to convert the string to xml. but i want to parse and get the status and i_numer which i need to use for further processing.can some one point me in right direction or give some hints.below is the xml i am using.
i tried the innerxml property from the Xdocument and XmlDocument which is returning the whole "" element and this is not what i needed.
<Report>
<Incidentreport Company="company1" ID="sample">
<status i_number="12345678" status="sucessful" />
</Incidentreport>
</Report>
The following should work:
string str = [string of xml goes here];
string i_number = string.Empty;
XmlDocument doc = new XmlDocument();
doc.Load(str);
XmlNode node = doc.SelectSingleNode("//status");
i_number = node.Attributes["i_number"].Value;
You can use SelectSingleNode() which accept XPath parameter to get the target attribute value in one go * :
var raw = #"<Report>
<Incidentreport Company='company1' ID='sample'>
<status i_number='12345678' status='sucessful' />
</Incidentreport>
</Report>";
var doc = new XmlDocument();
doc.LoadXml(raw);
var result = doc.SelectSingleNode("/Report/Incidentreport/status/#i_number");
Console.WriteLine(result.Value);
dotnetfiddle demo
*) notice how XML attribute can be referenced by using #attribute_name syntax in XPath
Hi i am facing an issue extracting innertext from an xml script saved as varchar2 in my oracle database.
While fetching i am getting the xml in the following format:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<SpecificAction xmlns=\"http://www.xyz.com/schemas/core/caut\">action to take</SpecificAction>"
the following xml is fetched using the code below:
instance.cautDescription = records.GetStringOrDefault("SPEC_ACTION");
the field SPEC_ACTION is of VARCHAR2(4000 BYTE) type.
due to the presence of \ character in the xml from database i am not able to extract the inner text withing the Tag. I tried the following code for fetching the inner text:
string s = instance.cautDescription;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(s);
XmlNode specificAction = xmlDoc.DocumentElement.SelectSingleNode("/SpecificAction");
string specific = specificAction.InnerText;
xmlString = specificAction.InnerText;
return xmlString;
My code is returning null can this be avoided if so how , any support would be really helpful.
This is classic problem when working with XML having default namespace. In XML, when you have default namespace (namespace without prefix, like xmlns="...."), all elements without prefix considered in default namespace. But in XPath, all elements without prefix considered has no namespace. To bridge this different paradigm, you need to declare a prefix that point to default namespace URI and use it in XPath :
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
XmlNode specificAction = xmlDoc.DocumentElement.SelectSingleNode("/ns:SpecificAction", nsManager);
string specific = specificAction.InnerText;
Since the "SpecificAction" node has a namespace, you will need to supply a namespace manager.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(s);
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("xyz", "http://www.xyz.com/schemas/core/caut");
XmlNode specificAction = xmlDoc.SelectSingleNode("/xyz:SpecificAction", ns);
return specificAction.InnerText;
I have a XML file, that looks like this inside:
<Data>
<INFO>
..
...
<JOB_NAME value="filename.pdf"/>
<useless_info value="some_info"/>
<TIMESTAMP value="20120210075304"/>
<more_useless_info value="012345"/>
...
..
</INFO>
<INFO>
..
...
<JOB_NAME value="filename2.pdf"/>
<useless_info value="some_info"/>
<TIMESTAMP value="20120210073487"/>
<more_useless_info value="012345"/>
...
..
</INFO>
</Data>
What i want to do, is write specific info to strings, so that later on i can write these to a text file or new XML file.
I found this example here: http://www.csharp-examples.net/xml-nodes-by-name/
And i have this code a little bit working.
Not fully, because it it not getting the values.
my code looks like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FileNameTextBox.Text);
XmlNodeList xnList = xmlDoc.SelectNodes("/Data/INFO");
foreach (XmlNode xn in xnList)
{
string jobName = xn["JOB_NAME"].InnerText;
string timeStamp = xn["TIMESTAMP"].InnerText;
MessageBox.Show(timeStamp + jobName); //for testing
}
I think this has to do with the fact that the info that i want to get, is not boxed in like <box>info</box>
What i cant find is how i could get the info in my caseout of the xml file now.
Could someone lent me a hand?
thank you!
You need to select the JOB_NAME and TIMESTAMP child nodes of each INFO node, then get their attributes, then get the Value of the "value" attribute.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FileNameTextBox.Text);
XmlNodeList xnList = xmlDoc.SelectNodes("/Data/INFO");
foreach (XmlNode xn in xnList)
{
string jobName = xn.SelectSingleNode("JOB_NAME").Attributes["value"].Value;
string timeStamp = xn.SelectSingleNode("TIMESTAMP").Attributes["value"].Value;
MessageBox.Show(timeStamp + jobName); //for testing
}
Be careful with this though as you are likely to get a NullReferenceException if any of the INFO nodes don't contain both a JOB_NAME and TIMESTAMP Node, and also if either of those do not have an attribute "value".
To answer your comment below:
string vendorName = xn.SelectSingleNode("JOB_NAME").Attributes["vendor-name"].Value;
string mediaName = xn.SelectSingleNode("JOB_NAME").Attributes["media-name"].Value;
You're correct in that innerText won't work because in your example 'value' is an attribute.
string jobName = xn["JOB_NAME"].Attributes["value"].Value;
string timeStamp = xn["TIMESTAMP"].Attributes["value"].Value;
Corrected and tested. This method or the SelectSingleNode should work fine.
If you want to iterate over all INFO elements and read the contained JOB_NAME and TIMESTAMPs valueattributes then Tobsey's answer is correct and will give you the desired result.
If you intend to query specific values from your Xml document you should use XPath queries instead of iterating over a set of nodes:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FileNameTextBox.Text);
string jobName = xmlDoc.SelectSingleNode("//JOB_NAME/#value").Value;
string timeStamp = xmlDoc.SelectSingleNode("//TIMESTAMP/#value").Value;
Update
If you have repeating INFO nodes but just are interested in the first one you could change your query to just look at the first one:
string jobName = xmlDoc.SelectSingleNode("//INFO[1]/JOB_NAME/#value").Value;
string timeStamp = xmlDoc.SelectSingleNode("//INFO[1]/TIMESTAMP/#value").Value;
The Xpath query //INFO[1]/JOB_NAME/#value is a shorthand expression for //INFO[position() = 1]/JOB_NAME/#value and will examine the position of the node in your Xml document.
Beware! The simplified example above will fail if .SelectSingleNode returns null!
You should get the Value property of the attribute named "value" in your nodes:
string jobName = xn.SelectSingleNode("JOB_NAME").Attributes["value"].Value;
I have some code that is returning a XNode to me which looks like this:
<File>
<Component>Main</Component>
<Path>C:\Main\</Path>
<FileName>main.txt</FileName>
</File>
I need to have some C# code that will be able to pull out the value of Path for example (C:\Main). I know that if I was using an XML node I could do it like this:
String filePath = xmlNode["Path"].InnerText;
Does anybody know what the equivalent would be for an XNode? Any help is much appreciated!
Do you have to have it returning an XNode rather than an XElement? With an XElement it's simpler than with an XNode:
string filePath = fileElement.Element("Path").Value;
That will find the first Path element, and will throw a NullReferenceException if there aren't any. An alternative if you're happy to get null if there aren't any would be:
string filePath = (string) fileElement.Element("Path");
If you're really stuck with XNode, you'll either have to cast to XElement or possibly XContainer.
You can convert your XNode into XElement to access to its properties, my example:
XNode lastNode = myXElement.LastNode;
//if I want to get the 'ID' attribute
string id = (lastNode as XElement).Attribute("ID").Value;
Casting XNode to XElement works for the individual element to retrieve its value or attributes. But you won't be able to use myXelement.Elements("XXX") to get nested elements. For that you can use xmlNode.Nodes().
This should work:
var nodes = xmlNode.Nodes();//Get all nodes under 'File'
var fileNameNode = nodes.Where(el => ((XElement)el).Name.LocalName == "FileName")
.FirstOrDefault();
string filePath = ((XElement)fileNameNode).Value;
You may use this:
XElement xtr = XElement.Load("path/to/your/xml/file");
String filePath = xtr.Descendants("Path").Single().Value;
If you import System.Xml.XPath you can use XPathSelectElement like this on the XNode object:
String component = xmlNode.XPathSelectElement("Component");
String path = xmlNode.XPathSelectElement("Path");
String fileName = xmlNode.XPathSelectElement("FileName");
It depends on what convcrete objets is the abstract XNode. From XNode Class:
XNode is an abstract common base class for the following types:
XComment
XContainer: can be XDocument or XElement
XDocumentType
XProcessingInstruction
XText
So you need to check if you can cast it to an XDocument or an XElement, and use their methods, or use LINQ to XML:
For example:
Best way to query XDocument with LINQ?
Querying an XDocument vs. Querying an XElement (C#)
XNode xnode
string value = (xnode as XElement).Value;
we can get the value form XElement object so we need to cast XNode to XElement first
should work