Loop through XML document using XPathNavigator - c#

I have the below XML, and I am trying to write values to a CSV file. I am however not sure how to proceed further, with everything I've tried throwing errors. The below returns:"Expression must evaluate to a node-set". Any assistance is appreciated.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<Envelope>
<Body>
<RESULT>
<SUCCESS>TRUE</SUCCESS>
<Mailing>
<MailingId>9285984</MailingId>
<ReportId>362040252</ReportId>
<ScheduledTS>2014-08-22 11:44:33.0</ScheduledTS>
<MailingName>305_ENDS</MailingName>
</Mailing>
<Mailing>
<MailingId>9278770</MailingId>
<ReportId>361956135</ReportId>
<ScheduledTS>2014-08-22 09:15:00.0</ScheduledTS>
<MailingName>141_TSI</MailingName>
<Visibility>Shared</Visibility>
</Mailing>
<Mailing>
<MailingId>9286460</MailingId>
<ReportId>362043622</ReportId>
<ScheduledTS>2014-08-22 12:57:30.0</ScheduledTS>
<MailingName>301_BRANDREP</MailingName>
</Mailing>
</RESULT>
</Body>
</Envelope>
C#:
xpathDoc = HttpHelper.HttpStream(xmlReq, sessionid);
XPathNavigator nav = xpathDoc.CreateNavigator();
XPathNodeIterator xmlIterator = nav.Select("/Envelope/Body/RESULT/");
var csv = new StringBuilder();
filePath = "C:\Campaigns.csv";
foreach (XPathNavigator node in xmlIterator)
{
string MailingId = node.SelectSingleNode("MailingId").Value;
string ReportId = node.SelectSingleNode("ReportId").Value;
string ScheduledTS = node.SelectSingleNode("ScheduledTS").Value;
string MailingName = node.SelectSingleNode("MailingName").Value;
string newLine = string.Format("{0},{1},{2},{3},{4}", MailingId, ReportId, ScheduledTS, MailingName, Environment.NewLine);
csv.Append(newLine);
}
File.WriteAllText(filePath, csv.ToString());

Well, you can try following approach:
foreach (XPathNavigator node in nav.Select("/Envelope/Body/RESULT/Mailing"))
{
string MailingId = node.SelectSingleNode("./MailingId").Value;
// and so on
Note: it should be exactly Mailing not RESULT as in your query, and should not ends with /

Change XPathNavigator node in nav.Select("/Envelope/Body/RESULT/") to XPathNavigator node in nav.Select("/Envelope/Body/RESULT/Mailing") and then use e.g. string MailingId = node.SelectSingleNode("MailingId").Value;.

Related

Get values of XML nodes with foreach

I am working on a programm with C# and a XML-File. I want to read the values of the xml-nodes but I get an issue with that. In the second part, where I am trying to get the content, it only does one loop and not three. The first values are correct. I don't know why it only makes the first loop. I hope someone can help me.
My XML-File:
<?xml version="1.0" encoding="utf-8"?>
<lagerverwaltung>
<article>
<inventory id="1">
</inventory>
<orders>
<order id="1">
<id>1</id>
<idposition>1</idposition>
<content>
<idarticle amount="4">2</idarticle>
<idarticle amount="3">3</idarticle>
<idarticle amount="2">1</idarticle>
</content>
<idcustomer>2</idcustomer>
<orderdate>05.01.2018 15:10:44</orderdate>
<paydate>05.02.2018</paydate>
<mwst>7.7</mwst>
<total>1781.358</total>
</order>
</orders>
</article>
</lagerverwaltung>
My C#-Code:
List<Order> orderList = new List<Order>();
XmlDocument xml = new XmlDocument();
xml.Load(xmlFilePath);
XmlNodeList xnList = xml.SelectNodes("/lagerverwaltung/article/orders/order");
foreach (XmlNode xn in xnList)
{
// Is working
string id = xn["id"].InnerText;
string bestellPositionId = xn["idposition"].InnerText;
string kundeId = xn["idcustomer"].InnerText;
string bestelldatum = xn["orderdate"].InnerText;
string rechnungsDatum = xn["paydate"].InnerText;
string mwst = xn["mwst"].InnerText;
string rechnungsTotal = xn["total"].InnerText;
XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[#id='" + id + "']/content");
Dictionary<string, string> content= new Dictionary<string, string>();
foreach (XmlNode xmlNode in xnInhalt) // Does only one loop
{
string articleid = xmlNode["idarticle"].InnerText;
string amount = xmlNode["idarticle"].GetAttribute("amount");
content.Add(articleid, amount);
}
}
There is a single content node, use content/idarticle to get the inner collection:
XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[#id='" + id
+ "']/content/idarticle");
You would then modify the following code because xmlNode now refers to an idarticle. For example,
string articleid = xmlNode.InnerText;

How to get node values in XML file using c#

I have an XML file, in this XML you can see the RESPONSE_DATA tag. This tag have some more inner tags. I need to get all the values inside PERSON_DATA tags. Also i need to get all the other value in below xml file.
<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n
<HUMAN_VERIFICATION xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RESPONSE_DATA>
<RESPONSE_STATUS>
<ERROR>100</ERROR>
<MESSAGE>successful</MESSAGE>
</RESPONSE_STATUS>
<CONTACT_NUMBER>3120202456011</CONTACT_NUMBER>
<PERSON_DATA>
<NAME>Alex</NAME>
<DATE_OF_BIRTH>10-9-1982</DATE_OF_BIRTH>
<BIRTH_PLACE>Washington</BIRTH_PLACE>
<EXPIRY>2020-12-15</EXPIRY>
</PERSON_DATA>
<CARD_TYPE>idcard</CARD_TYPE>
</RESPONSE_DATA>
</HUMAN_VERIFICATION>
I prefer using Linq to Xml.
var results = doc.Descendants("PERSON_DATA") // Flatten the hierarchy and look for PERSON_DATA
.Select(x=> new
{
NAME = (string)x.Element("NAME"),
DATE_OF_BIRTH = (string)x.Element("DATE_OF_BIRTH"),
BIRTH_PLACE = (string)x.Element("BIRTH_PLACE"),
EXPIRY = (string)x.Element("EXPIRY"),
});
Check the Demo
You can try this code it may be helpful for you.
XmlDocument newdoc = new XmlDocument();
newdoc.InnerXml = " <?xml version=\"1.0\" encoding=\"utf-16\"?><HUMAN_VERIFICATION><RESPONSE_DATA><RESPONSE_STATUS><ERR>100</ERROR><MESSAGE>successful</MESSAGE></RESPONSE_STATUS><CONTACT_NUMBER>3120202456011</ CONTACT _NUMBER><PERSON_DATA><NAME>Alex</NAME><DATE_OF_BIRTH>10-9-1982</DATE_OF_BIRTH><BIRTH_PLACE>Washington</BIRTH_PLACE><EXPIRY>2020-12-15</EXPIRY></PERSON_DATA><CARD_TYPE>idcard</CARD_TYPE></RESPONSE_DATA></HUMAN_VERIFICATION>";
var selectnode = "HUMAN_VERIFICATION/RESPONSE_DATA/PERSON_DATA";
var nodes = newdoc.SelectNodes(selectnode);
foreach (XmlNode nod in nodes)
{
string name = nod["NAME" ].InnerText;
string dob = nod["DATE_OF_BIRTH"].InnerText;
string place = nod["BIRTH_PLACE" ].InnerText;
string expiry = nod["EXPIRY" ].InnerText;
Console.WriteLine("Person: {0} {1} {2} {3}", name, dob, place, expiry);
}
It's really easy and intuitive with System.Xml.Linq.
var xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<HUMAN_VERIFICATION xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <RESPONSE_DATA>\r\n <RESPONSE_STATUS>\r\n <ERROR>100</ERROR>\r\n <MESSAGE>successful</MESSAGE>\r\n </RESPONSE_STATUS>\r\n <CONTACT_NUMBER>3120202456011</CONTACT_NUMBER>\r\n <PERSON_DATA>\r\n <NAME>Alex</NAME>\r\n <DATE_OF_BIRTH>10-9-1982</DATE_OF_BIRTH>\r\n <BIRTH_PLACE>Washington</BIRTH_PLACE>\r\n <EXPIRY>2020-12-15</EXPIRY>\r\n </PERSON_DATA>\r\n <CARD_TYPE>idcard</CARD_TYPE>\r\n </RESPONSE_DATA>\r\n</HUMAN_VERIFICATION>";
var document = XDocument.Parse(xml);
var name = document.Element("HUMAN_VERIFICATION").Element("RESPONSE_DATA").Element("PERSON_DATA").Element("NAME").Value;
OR
var personData = document.Element("HUMAN_VERIFICATION").Element("RESPONSE_DATA").Element("PERSON_DATA").Elements().ToDictionary(e => e.Name.ToString(), e => e.Value);

Select single node

From the following xml:
<response>
<content>
<Result xmlns="http://www.test.com/nav/webservices/types">
<Name>Test</Name>
</Result>
</content>
<status>ok</status>
</response>
I am trying to get the value of the Name element the following way but that does not work:
private static void Main()
{
var response = new XmlDocument();
response.Load("Response.xml");
var namespaceManager = new XmlNamespaceManager(response.NameTable);
namespaceManager.AddNamespace("ns", "http://www.test.com/nav/webservices/types");
Console.WriteLine(response.SelectSingleNode("/response/content/Result/Name", namespaceManager).InnerXml);
}
How can I select the Name element?
Your code would have worked just fineif the Xml had defined the namespace with a "ns:" prefix.
But in this case, the namespace is given without any prefix, which sets the default namespace for everything in the Result tag to ".../webservice/types".
To reflect this, you need to modify the Xpath, and tell the XmlDocument that the nodes you are looking for under Resultare in the webservice/types namespace. So your query will look like this:
Console.WriteLine(response.SelectSingleNode(#"/response/content/ns:Result/ns:Name", namespaceManager).InnerXml);
For getting directly the text value of a node there is a text() function, if used in the query it would look like:
/response/content/Result/Name/text()
Try this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = "<response><content><Result xmlns=\"http://www.test.com/nav/webservices/types\"><Name>Test</Name></Result></content><status>ok</status>";
string elementValue = String.Empty;
if (xmlDoc != null)
{
xNode = xmlDoc.SelectSingleNode("/Result");
xNodeList = xNode.ChildNodes;
foreach (XmlNode node in xNodeList)
{
elementValue = node.InnerText;
}
}

Adding info to a xml file

I have a XML file which contains about 850 XML nodes. Like this:
<NameValueItem>
<Text>Test</Text>
<Code>Test</Code>
</NameValueItem>
........ 849 more
And I want to add a new Childnode inside each and every Node. So I end up like this:
<NameValueItem>
<Text>Test</Text>
<Code>Test</Code>
<Description>TestDescription</Description>
</NameValueItem>
........ 849 more
I've tried the following:
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
XmlNodeList nodes = doc.GetElementsByTagName("NameValueItem");
Which gives me all of the nodes, but from here am stuck(guess I need to iterate over all of the nodes and append to each and every) Any examples?
You need something along the lines of this example below. On each of your nodes, you need to create a new element to add to it. I assume you will be getting different values for the InnerText property, but I just used your example.
foreach (var rootNode in nodes)
{
XmlElement element = doc.CreateElement("Description");
element.InnerText = "TestDescription";
root.AppendChild(element);
}
You should just be able to use a foreach loop over your XmlNodeList and insert the node into each XmlNode:
foreach(XmlNode node in nodes)
{
node.AppendChild(new XmlNode()
{
Name = "Description",
Value = [value to insert]
});
}
This can also be done with XDocument using LINQ to XML as such:
XDocument doc = XDocument.Load(xmlDoc);
var updated = doc.Elements("NameValueItem").Select(n => n.Add(new XElement() { Name = "Description", Value = [newvalue]}));
doc.ReplaceWith(updated);
If you don't want to parse XML using proper classes (i.e. XDocument), you can use Regex to find a place to insert your tag and insert it:
string s = #"<NameValueItem>
<Text>Test</Text>
<Code>Test</Code>
</NameValueItem>";
string newTag = "<Description>TestDescription</Description>";
string result = Regex.Replace(s, #"(?<=</Code>)", Environment.NewLine + newTag);
but the best solution is Linq2XML (it's much better, than simple XmlDocument, that is deprecated at now).
string s = #"<root>
<NameValueItem>
<Text>Test</Text>
<Code>Test</Code>
</NameValueItem>
<NameValueItem>
<Text>Test2</Text>
<Code>Test2</Code>
</NameValueItem>
</root>";
var doc = XDocument.Load(new StringReader(s));
var elms = doc.Descendants("NameValueItem");
foreach (var element in elms)
{
element.Add(new XElement("Description", "TestDescription"));
}
var text = new StringWriter();
doc.Save(text);
Console.WriteLine(text);

Get specific values from Xml

I don't how to extract the values from XML document, and am looking for some help as I'm new to C#
I am using XmlDocument and then XmlNodeList for fetching the particular XML document
Here is my code
XmlNodeList XMLList = doc.SelectNodes("/response/result/doc");
And my XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>
<doc>
<long name="LoadID">494</long>
<long name="EventID">5557</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
<doc>
<long name="LoadID">774</long>
<long name="EventID">5558</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
</result>
</response>
In this i have to fetch every the XMLData data that is under every doc tag and i have to fetch last doc tag EventID.
var xml = XDocument.Parse(xmlString);
var docs = xml.Root.Elements("doc");
var lastDocEventID = docs.Last()
.Elements("long")
.First(l => (string)l.Attribute("name") == "EventID")
.Value;
Console.WriteLine ("Last doc EventId: " +lastDocEventID);
foreach (var doc in docs)
{
Console.WriteLine (doc.Element("str").Element("TransactionDate").Value);
}
prints:
Last doc EventId: 5558
2014-05-28T14:17:31.2186777-06:00
2014-05-28T14:17:31.2186777-06:00
You can use two XPath expressions to select the nodes you want. To answer each part of your question in turn:
To select all of the XMLData nodes:
XmlNodeList XMLList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
To select the last EventId:
XmlNode lastEventIdNode =
doc.SelectSingleNode("/response/result/doc[position() =
last()]/long[#name='EventID']");
If not all doc nodes are guaranteed to have an event id child node, then you can simply:
XmlNodeList eventIdNodes =
doc.SelectNodes("/response/result/doc[long[#name='EventID']]");
XmlNode lastNode = eventIdNodes[eventIdNodes.Count - 1];
That should give you what you've asked for.
Update;
If you want the XML data inside each strXml element, you can use the InnerXml property:
XmlNodeList xmlList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
foreach(XmlNode xmlStrNode in xmlList)
{
string xmlInner = xmlStrNode.InnerXml;
}
There's one result tag short in your xml.
Try using this. It's cleaner too imho
XmlNodeList docs = doc.SelectSingleNode("response").SelectSingleNode("result").SelectNodes("doc");
Then you can use a combination of SelectSingleNode, InnerText, Value to get the data from each XmlNode in your list.
For example if you want the EventID from the first doc tag:
int eventID = int.Parse(docs[0].SelectSingleNode("long[#name='EventID']").InnerText);

Categories

Resources