I am trying to fetch the value for name attribute but unable to do it.
<Person>
<DOB localDate="2015-07-02" utcDate="2015-07-02" localTime="09:26:00" utcTime="08:26:00" />
<Info name="Bruce Wayne" Country="GB" Zone="3" />
</Person>
Try This:
string str= "";
XmlDocument xdoc = new XmlDocument();
xdoc.Load("Your XML Path");
XmlNodeList elements = xdoc.GetElementsByTagName("Info");
for (int i = 0; i < elements.Count; i++)
{
str= elements[i].Attributes["name"].Value;
}
MessageBox.Show(str);
Unless you have a specific reason for using an XmlDocument, use the newer XDocument instead, linq makes finding xml nodes very easy.
Try this
var name = xDoc.Root.Element("Info").Attribute("name").Value;
Related
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;
}
}
This question already has answers here:
SelectSingleNode returns null when tag contains xmlNamespace
(4 answers)
Closed 7 years ago.
I am using SelectNodes to read xml nodes but i am getting null when i try GetElementsByTagName i get the values.
XmlDocument xml = new XmlDocument();
xml.Load(DownloadFile);
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
for (int i = 0; i < xmlnode.Count; i++)
{
XmlNodeList rooms = xml .SelectNodes("RoomSize/CruisePriceSummaryRoomSize");
for(int j = 0; j < rooms.Count; j++)
{
string bestFare = rooms[j].SelectSingleNode("BestFare/TotalPrice").InnerText;
string fullFare = rooms[j].SelectSingleNode("FullFare/TotalPrice").InnerText;
// do whatever you need
}
}
I want to read TotalPrice from BestFare and FullFare Each child has two innerchilds BestFare and FullFareand I need to read each TotalPrice.
This is my XML
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCruisePriceSummaryResponse
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/OpenseasAPI.ServiceModel">
<CruisePriceSummaryResponse>
<AvailablePromos
xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>FLA</d3p1:string>
<d3p1:string>FLB</d3p1:string>
</AvailablePromos>
<Brand>PA</Brand>
<CruiseCategory i:nil="true"/>
<RoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>2798.0000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>3198.000000</TotalPrice>
</FullFare>
<PaxCount>2</PaxCount>
</CruisePriceSummaryRoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>2796.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>4196.000000</TotalPrice>
</FullFare>
<PaxCount>4</PaxCount>
</CruisePriceSummaryRoomSize>
</RoomSize>
<ShipCode>PD</ShipCode>
</CruisePriceSummaryResponse>
<CruisePriceSummaryResponse>
<AvailablePromos
xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>FLA</d3p1:string>
<d3p1:string>LF1</d3p1:string>
</AvailablePromos>
<Brand>PA</Brand>
<RoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>1298.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>3498.000000</TotalPrice>
</FullFare>
<PaxCount>2</PaxCount>
</CruisePriceSummaryRoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>1796.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>5396.000000</TotalPrice>
</FullFare>
<PaxCount>4</PaxCount>
</CruisePriceSummaryRoomSize>
</RoomSize>
<ShipCode>PJ</ShipCode>
</CruisePriceSummaryResponse>
</ArrayOfCruisePriceSummaryResponse>
Help would be appreciated. I do not want to use linq as this is a SSIS project using VS2008 and it doesnot support linq.
Thanks in advance
You never load or read the source XML. Your code
XmlDocument xml = new XmlDocument();
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
creates an empty XML document, and then tries to get elements from the empty xml.
You need to call XmlDocument.Load or XmlDocument.LoadXML to read the xml from a file or a string.
XmlDocument xml = new XmlDocument();
xml.Load("pathtosomefile.xml");
XmlNodeList xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
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;.
I'm trying to parse the following:
<?xml version="1.0" encoding="utf-8"?>
<GC>
<CREATED>01/23/2014 16:10:18</CREATED>
<DATA>
<CONTAINER name="home" type="xml" version="1.1.0.0">
<HEADER>
<ATTRIBUTE name="lang" value="EN" />
<ATTRIBUTE name="destination" value="UK" />
</HEADER>
</CONTAINER>
</DATA>
</GC>
How do I go about finding the value when name="lang"?
So far I have this:
XmlDocument Doc = new XmlDocument();
Doc.Load(#path);
XmlNode node = Doc.DocumentElement.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE/NAME");
string SI = node.Attributes["lang"].InnerText;
Doesn't seem to work unfortunately, could use some help. Many thanks.
This will do it:
XmlNode node =
Doc.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[#name = 'lang']/#value");
string SI = node.InnerText;
And I would advise using a null check:
XmlNode node =
Doc.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[#name = 'lang']/#value");
string SI = null;
if(node != null)
{
SI = node.InnerText;
}
With using LINQ to XML you can get it like this:
XDocument xDoc = XDocument.Load("path");
var element = xDoc.Descendans("ATTRIBUTE").First();
var nameAttribute = (string)element.Attribute("name");
This will get you the value of the attribute in the ATTRIBUTE tag which has name == lang:
XmlDocument Doc = new XmlDocument();
Doc.Load(#path);
XmlNode node = Doc.DocumentElement.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[#name='lang']");
string SI = node.Attributes["value"].InnerText;
XmlNode node = Doc.DocumentElement.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[#name='lang']");
string SI = node.Attributes["value"].Value;
I've got it writing the XML doc fine, and it will look something like this
<Team>
<Character Name="Bob" Class="Mage"/>
<Character Name="Mike" Class="Knight"/>
</Team>
I'm trying to find a way to access "Class" attribute of a single character and modify it. So far, i've got it to the point where I can pinpoint a specific character, but I can't figure out how to access the 'Class' attribute and modify it for the char.
void Write(string path, string charName, string varToChange, string value){
XmlNode curNode = null;
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement rootDoc = doc.DocumentElement;
curNode = rootDoc;
if(curNode.HasChildNodes){
for(int i=0; i<curNode.ChildNodes.Count; i++){
if(charName == curNode.ChildNodes[i].Attributes.GetNamedItem("Name").Value){
// Code would go here
}
}
}
return;
}
Use XPATH:
XmlDocument doc = new XmlDocument();
doc.Load(path);
var nodes = doc.SelectNodes(String.Format("/Team/Character[#Name=\"{0}\"]", charName));
foreach (XmlElement n in nodes)
{
n.SetAttribute(varToChange, value);
}
Use the XmlElement.SetAttribute('attribute to modify', 'value to set it to') method
edit:
I just noticed you were using XMLNode instead of XMLElement, so in order to update the attribute you can either just cast the XmlNode to an XmlElement like so
XmlElement el = (XmlElement)curNode;
el.SetAttribute("Class", "Value");
Otherwise you can create an attribute and then append it in order to update the attribute:
XmlAttribute attrib =
curNode.OwnerDocument.CreateAttribute("Class");
attrib.Value = "Value";
curNode.Attributes.Append(attrib);
Hope this helps