Been working a lot with Google Checkout and the responses are always huge amount of XML data. What i want is to parse out the node called merchant-private-data from this rubble.
It might not always be present and it might be on several positions (with the same value).
I tried a simple approach but that did not yield any results.
From the sandbox response:
<?xml version="1.0" encoding="UTF-8"?>
<authorization-amount-notification xmlns="http://checkout.google.com/schema/2" serial-number="123456789">
<authorization-amount currency="USD">11.65</authorization-amount>
<authorization-expiration-date>2012-08-21T12:30:16.000Z</authorization-expiration-date>
<avs-response>Y</avs-response>
<cvn-response>U</cvn-response>
...
<order-summary>
...
<shopping-cart>
...
<merchant-private-data>
<MERCHANT_DATA_HIDDEN>50c77071-aeea-40fe-962b-f4d51d1f9b0</MERCHANT_DATA_HIDDEN>
</merchant-private-data>
...
</shopping-cart>
...
</order-summary>
</authorization-amount-notification>
Might be in more locations and might not always be in that location.
My idea was this, but it did not work (yields 0 results even though i can see the node in the xml):
XDocument input = XDocument.Parse(xmldata);
string privateData = null;
var privateDataNode = (from nodes in input.Descendants("merchant-private-data") select nodes).FirstOrDefault();
if (privateDataNode != null && privateDataNode.HasElements && privateDataNode.Element("MERCHANT_DATA_HIDDEN") != null)
privateData = privateDataNode.Element("MERCHANT_DATA_HIDDEN").Value;
You're missing namespace, try it like this:
XDocument input = XDocument.Parse(xmldata);
XNamespace ns = input.Root.Name.Namespace;
string privateData = null;
var privateDataNode = (from nodes in input.Descendants(ns + "merchant-private-data") select nodes).FirstOrDefault();
if (privateDataNode != null && privateDataNode.HasElements && privateDataNode.Element(ns + "MERCHANT_DATA_HIDDEN") != null)
privateData = privateDataNode.Element(ns + "MERCHANT_DATA_HIDDEN").Value;
Related
I have a XML Doc that I'm pulling out a specific Node and all of it's attributes. In debug mode I can see that I'm getting the specific Nodes and all of their attributes. However, when I try to get the attribute value it can't find it and returns a NULL value. I've done some searching and looked at some examples and from what I can tell I should be getting the value but I'm not and I don't see what I'm doing wrong.
I'm trying to get the StartTime value.
Here is the XML that is returned.
Here you can see in debug and with the Text Visualizer the value should be there.
The code I'm trying.
XmlNodeList nodes = xmlDoc.GetElementsByTagName("PlannedAbsences");
if (nodes != null && nodes.Count > 0)
{
foreach (XmlNode node in nodes)
{
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["StartTime"];
if (nameAttribute != null)
{
//var startDate = nameAttribute.Value;
}
}
}
}
Using the XDocument class contained within the System.Xml.Linq namespace, grab the sub elements from the PlannedAbsences parent, then iterate over sub elements retrieving the value of the desired attribute.
var xmlDoc = XDocument.Load(#"path to xml file")
var absences = xmlDoc.Element("PlannedAbsences")?.Elements("Absence");
foreach (var item in absences)
{
var xElement = item.Attribute("StartTime").Value;
Console.WriteLine(xElement);
}
My xml looks like this....
<?xml version="1.0" encoding="utf-8"?>
<messwerte>
<messwert>
<tag>1</tag>
<niederschlag>46</niederschlag>
<temperatur>7,6</temperatur>
<druck>4,6</druck>
</messwert>
......
</messwerte>
Now, I wanna give a a specific day where I want to change "niederschlag" "temperatur" and "druck" and I tried this:
public static void WriteXML(int day, double[] mess, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement nieder = doc.SelectSingleNode("/messwerte/messwert" + Convert.ToString(day) + "/niederschlag") as XmlElement;
if (nieder != null)
{
nieder.InnerText = Convert.ToString(mess[0]);
}
}
And it wont work.
And I know it's baaaad and super basic but i cant get it to work.......
I would suggest the reason it won't work for you, is you're trying to do 2 different things with one xpath string.
First you have to find the messwert element with a tag element that has an InnerText value matching the day value you're passing in.
Once you've identified the right element you want to change the InnerText of the niederschlag element.
Even though writing this out makes it seem quite complicated, leveraging a LINQ query can simplify it tremendously:
public static void WriteXML(int day, double[] mess, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
var nieder = (from XmlElement element in doc.GetElementsByTagName("messwert")
where element.SelectSingleNode("tag").InnerText == day.ToString()
select element).First().SelectSingleNode("niederschlag");
if (nieder != null)
{
nieder.InnerText = mess[0].ToString();
}
doc.Save(path);
}
This code assumes your data is strongly controlled and that you'll never be looking for a day that isn't there.
If this isn't the case you'll have to assign the query including the First() method to a temporary variable, and check if it's null.
Something like this should work:
public static void WriteXML(int day, double[] mess, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
var messwert = (from XmlElement element in doc.GetElementsByTagName("messwert")
where element.SelectSingleNode("tag").InnerText == day.ToString()
select element).FirstOrDefault();
if(messwert == null)
{
throw new ArgumentException($"The day value, doesn't exist. the value passed is {day}");
}
var nieder = messwert.SelectSingleNode("niederschlag");
if (nieder != null)
{
nieder.InnerText = mess[0].ToString();
}
doc.Save(path);
}
I've tried deleting a node from my XML file 3 different ways; and each way I've come up empty. I am querying a SQL database and grabbing a filename, I want to delete the entire node were the file name in the XML document is = to the SQL database result.
I'm not sure what's wrong in my code:
Background Information
fn44 is the Filename grabbed from a SQL database (all my info is in a
SQL table, I need an XML file for use with JavaScript)
XML:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<bannerMain>
<department>main</department>
<filename>resdrop.png</filename>
<title>This is a Title</title>
<text><![CDATA[caption text]]></text>
</bannerMain>
</xml>
Attempt 1 (I know that I'm not getting to the child correctly, can't seem to figure out how to fix it):
XDocument doc = XDocument.Load(Server.MapPath("~/uploads/banners.xml"));
var q = from node in doc.Descendants("bannerMain")
let fina = node.Descendants("filename")/*PROBLEM LINE*/
where fina != null && fina == myReader[0]/*Gets filename from SQL database*/
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save(Server.MapPath("~/uploads/banners.xml"));
Attempt 2 (should work in my mind but doesn't)
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/uploads/banners.xml"));
XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/xml/bannerMain[#filename="
+ fn44 + "]");
if (nodeToDelete != null)
{
nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
}
xmlDoc.Save(Server.MapPath("~/uploads/banners.xml"));
Attempt 3 (similar to attempt 2)
string nodeToDelete = fn44;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/uploads/banners.xml"));
XmlNode node = xmlDoc.SelectSingleNode(string.Format("//*[filename=\"{0}\"]"
, nodeToDelete));
if (node != null)
xmlDoc.SelectSingleNode("xml/bannersMain").RemoveChild(node);
xmlDoc.Save(Server.MapPath("~/uploads/banners.xml"));
I want to delete the whole node where the filename is = to the filename that is grabbed from the SQL database. Any help/resources is much appreciated.
SOLVED:
There's a few different options in the below answers that work out well.
Solution 1:
var xDoc = XDocument.Load(Server.MapPath("~/uploads/banners.xml"));
string fileName = fn44; //Use whatever value you found in SQL DB...
xDoc.Descendants("filename").Where(c => c.Value == fileName).Select(x => x.Parent).Remove();
xDoc.Save(Server.MapPath("~/uploads/banners.xml"));
Solution 2:
XDocument doc = XDocument.Load(Server.MapPath("~/uploads/banners.xml"));
var q = from node in doc.Descendants("bannerMain")
let fina = node.Element("filename")
where fina != null && fina.Value == fn44
select node;
q.Remove();
doc.Save(Server.MapPath("~/uploads/banners.xml"));
That seems to work for me:
string xmlfile = Server.MapPath("~/uploads/banners.xml");
var xDoc = XDocument.Load(xmlfile);
string fileName = "resdrop.png"; // Value from SQL DB
xDoc.Descendants("filename")
.Where(c => c.Value == fileName)
.Select(x => x.Parent)
.Remove();
xDoc.Save(xmlfile);
Your problem with attempt #1 is that you are trying to compare an IEnumerable<XElement> to your reader value, this should work (assuming each bannerMain only has a single filename element):
var q = from node in doc.Descendants("bannerMain")
let fina = node.Element("filename")//only single filename, so get just that XElement
where fina != null && fina.Value == reader[0]//assumes reader[0] is a string value
select node;
To remove them just do this:
q.Remove();
doc.Save(Server.MapPath("~/uploads/banners.xml"));
I ran this through LINQPad and after doing q.Remove();, here were the contents of doc: <xml />.
It's a little verbose but here is a non-linq snippet:
void DeleteNode(string fileName)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/uploads/banners.xml"));
//Get all the bannerMain nodes.
XmlNodeList nodelist = doc.SelectNodes("/xml//bannerMain");
if (nodelist != null)
{
foreach (XmlNode node in nodelist)
{
//Look for then filename child. If it contains desired value
//delete the entire bannerMain node. Assumes order of child nodes
//may not be a constant.
foreach (XmlNode child in node.ChildNodes)
{
if (child.Name == "filename" && child.InnerText == name)
{
node.ParentNode.RemoveChild(node);
}
}
}
doc.Save(Server.MapPath("~/uploads/banners.xml"));
}
}
For Attempt #2, remove the # sign for the filename. The # symbol represents an Attribute, but the filename is a child-node.
If your phrase doesn't work, I'd rephrase it a little from:
"/xml/bannerMain[filename=
to
"//bannerMain[filename=
I am sure that this is basic and probably was asked before, but I am only starting using Linq to XML.
I have a simple XML that i need to read and write to.
<Documents>
...
<Document>
<GUID>09a1f55f-c248-44cd-9460-c0aab7c017c9-0</GUID>
<ArchiveTime>2012-05-15T14:27:58.5270023+02:00</ArchiveTime>
<ArchiveTimeUtc>2012-05-15T12:27:58.5270023Z</ArchiveTimeUtc>
<IndexDatas>
<IndexData>
<Name>Name1</Name>
<Value>Some value</Value>
<DataType>1</DataType>
<CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime>
<CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc>
</IndexData>
<IndexData>
<Name>Name2</Name>
<Value>Some value</Value>
<DataType>3</DataType>
<CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime>
<CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc>
</IndexData>
...
</IndexDatas>
</Document>
...
</Documents>
I have a "Documents" node that contains bunch of "Document" nodes.
I have GUID of the document and a "IndexData" name.
I need to find the document by GUID and check if it has "IndexData" with some name.
If it does not have it i need to add it.
Any help would be apreciated, as i have problem with reading and searching trough elements.
Currently I am trying to use (in C#):
IEnumerable<XElement> xmlDocuments = from c in XElement
.Load(filePath)
.Elements("Documents")
select c;
// fetch document
XElement documentElementToEdit = (from c in xmlDocuments where
(string)c.Element("GUID").Value == GUID select c).Single();
EDIT
xmlDocuments.Element("Documents").Elements("Document")
This returns no result, even tho xmlDocuments.Element("Documents") does. It looks like i cant get Document nodes from Documents node.
You can find those docs (docs without related name in index data) with below code, after that you could add your elements to the end of IndexData elements.
var relatedDocs = doc.Elements("Document")
.Where(x=>x.Element("GUID").Value == givenValue)
.Where(x=>!x.Element("IndexDatas")
.Elements("IndexData")
.Any(x=>x.Element("Name") == someValue);
This should work:
var x = XDocument.Load(filePath);
// guid in your sample xml is not a valid guid, so I changed it to a random valid one
var requiredGuid = new Guid("E61D174C-9048-438D-A532-17311F57ED9B");
var requiredName = "Name1";
var doc = x.Root
.Elements("Document")
.Where(d => (Guid)d.Element("GUID") == requiredGuid)
.FirstOrDefault();
if(doc != null)
{
var data = doc.Element("IndexDatas")
.Elements("IndexData")
.Where(d => (string)d.Element("Name") == requiredName)
.FirstOrDefault();
if(data != null)
{
// index data found
}
else
{
// index data not found
}
}
else
{
// document not found
}
We are getting an XML document from a vendor that we need to perform an XSL transform on using their stylesheet so that we can convert the resulting HTML to a PDF. The actual stylesheet is referenced in an href attribute of the ?xml-stylesheet definition in the XML document. Is there any way that I can get that URL out using C#? I don't trust the vendor not to change the URL and obviously don't want to hardcode it.
The start of the XML file with the full ?xml-stylesheet element looks like this:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="http://www.fakeurl.com/StyleSheet.xsl"?>
As a processing instruction can have any contents it formally does not have any attributes. But if you know there are "pseudo" attributes, like in the case of an xml-stylesheet processing instruction, then you can of course use the value of the processing instruction to construct the markup of a single element and parse that with the XML parser:
XmlDocument doc = new XmlDocument();
doc.Load(#"file.xml");
XmlNode pi = doc.SelectSingleNode("processing-instruction('xml-stylesheet')");
if (pi != null)
{
XmlElement piEl = (XmlElement)doc.ReadNode(XmlReader.Create(new StringReader("<pi " + pi.Value + "/>")));
string href = piEl.GetAttribute("href");
Console.WriteLine(href);
}
else
{
Console.WriteLine("No pi found.");
}
Linq to xml code:
XDocument xDoc = ...;
var cssUrlQuery = from node in xDoc.Nodes()
where node.NodeType == XmlNodeType.ProcessingInstruction
select Regex.Match(((XProcessingInstruction)node).Data, "href=\"(?<url>.*?)\"").Groups["url"].Value;
or linq to objects
var cssUrls = (from XmlNode childNode in doc.ChildNodes
where childNode.NodeType == XmlNodeType.ProcessingInstruction && childNode.Name == "xml-stylesheet"
select (XmlProcessingInstruction) childNode
into procNode select Regex.Match(procNode.Data, "href=\"(?<url>.*?)\"").Groups["url"].Value).ToList();
xDoc.XPathSelectElement() will not work since it for some reasone cannot cast an XElement to XProcessingInstruction.
You can also use XPath. Given an XmlDocument loaded with your source:
XmlProcessingInstruction instruction = doc.SelectSingleNode("//processing-instruction(\"xml-stylesheet\")") as XmlProcessingInstruction;
if (instruction != null) {
Console.WriteLine(instruction.InnerText);
}
Then just parse InnerText with Regex.
To find the value using a proper XML parser you could write something like this:
using(var xr = XmlReader.Create(input))
{
while(xr.Read())
{
if(xr.NodeType == XmlNodeType.ProcessingInstruction && xr.Name == "xml-stylesheet")
{
string s = xr.Value;
int i = s.IndexOf("href=\"") + 6;
s = s.Substring(i, s.IndexOf('\"', i) - i);
Console.WriteLine(s);
break;
}
}
}
private string _GetTemplateUrl(XDocument formXmlData)
{
var infopathInstruction = (XProcessingInstruction)formXmlData.Nodes().First(node => node.NodeType == XmlNodeType.ProcessingInstruction && ((XProcessingInstruction)node).Target == "mso-infoPathSolution");
var instructionValueAsDoc = XDocument.Parse("<n " + infopathInstruction.Data + " />");
return instructionValueAsDoc.Root.Attribute("href").Value;
}
XmlProcessingInstruction stylesheet = doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;