Display single value Of FirstChild Elements in XML - c#

Please, Help me Out Here
I Want to display the value of "email" from xml. my syntax works for now but it displays every value. i want to be able to display Individual (one) Values like
email: mail#mail.com
My scripts
var xml ="<?xml version='1.0' encoding='UTF-8'?>
<MemResponse>
<Phone>2554535</Phone>
<Email>mail#mail</Email>
<Number>we75546654</Number>
</MemResponse>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach(XmlNode n in doc.DocumentElement)
{
string q = n.FirstChild.InnerText;
Response.Write(q);
}

Simply you can select all element by tag name by GetElementsByTagName method.
Check this :
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var myEmails = doc.GetElementsByTagName("Email");
foreach (XmlNode mail in myEmails)
{
string mailText = mail.FirstChild.InnerText;
Response.Write(mailText);
}
I have got it from MSDN

Your code goes through each node and writes the contents of that node.
It seems like you want to match on the node name, and only write the value if its name is "email".
If thats the case, inside of your for each, try something like:
if(n.Name == "Email") {
string q = n.FirstChild.InnerText;
Response.Write(q);
}
Alternatively, you could just use a node list.
NodeList nl = doc.GetElementsByTagName("Email");
And write that.
When loading your XML Doc, use :
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());

Please try this code:
XmlDocument doc = new XmlDocument();
doc.LoadXml("YOUR_XML_PATH");
XmlNodeList email_hd= doc.GetElementsByTagName("Email");
string email=email_hd[0].InnerText;

Related

change xml value in c#

I am working on this since yesterday. I have an XML file which looks something like this
<catalog>
<captureInfo>
<row>5</row>
<col>5</col>
</captureInfo>
<patientInfo>
<name>XYZ</name>
<detail>details here</detail>
</patientInfo>
<imageData>
<r0c0>
<contrastFlag>true</contrastFlag>
</r0c0>
<r0c1>
<contrastFlag>true</contrastFlag>
</r0c1>
</imageData>
</catalog>
I need to update the value of contrastFlag in the XML file. This is the code I have written:
XmlDocument doc = new XmlDocument();
XmlNodeList imageData = doc.GetElementsByTagName("imageData");
foreach(XmlNode node in imageData)
{
foreach (XmlNode innernode in node)
{
if (innernode.Name == "r0c0")
{
innernode.InnerText = "false";
}
}
}
doc.Save("XMLFile1.xml");
Can anyone tell me where am I going wrong and also is there any better/faster approach for this?
Well first off, your XML is malformed, the closing should match "catalog". Why not just do this:
string xml = #"<catalog>
<captureInfo>
<row>5</row>
<col>5</col>
</captureInfo>
<patientInfo>
<name>XYZ</name>
<detail>details here</detail>
</patientInfo>
<imageData>
<r0c0>
<contrastFlag>true</contrastFlag>
</r0c0>
<r0c1>
<contrastFlag>true</contrastFlag>
</r0c1>
</imageData>
</catalog>";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
xdoc.SelectSingleNode("//catalog/imageData/r0c0/contrastFlag").InnerText = "false";
Here is a way to replace all of the instances using LINQ. I just wrote out to a new file to preserve the source.
StreamReader stream = new StreamReader(#"c:\test.xml");
XDocument doc = XDocument.Load(stream);
IEnumerable<XElement> flags = doc.Descendants("contrastFlag");
foreach (XElement e in flags)
{
e.Value = "false";
}
doc.Save(#"c:\test2.xml");

Get City Name from Reverse Geocoding with latitude and longitude

http://maps.googleapis.com/maps/api/geocode/xml?latlng=39.952853,32.901470&sensor=false
In this xml url, I couldn't get data from area which is explained in the below.
<long_name>Altınevler Mahallesi</long_name>
I'm using asp.net c#. Could you help me with this?
This is the code I tried to get the data from xml
XmlDocument xdoc = new XmlDocument();
xdoc.Load(
"http://maps.googleapis.com/maps/api/geocode/xml?latlng=39.952853,32.901470&sensor=false"
);
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");
foreach (XmlNode xNode in xNodelst)
{
label1.Text += "read";
}
I solved my question if anyone wants know be my guess. Solution indicated in the below.
Thank you
XmlDocument xDoc = new XmlDocument();
xDoc.Load("https://maps.googleapis.com/maps/api/geocode/xml?latlng=" +coordinate+"&location_type=ROOFTOP&result_type=street_address&key=YOURAPIKEY");
XmlNodeList xNodelst = xDoc.GetElementsByTagName("result");
XmlNode xNode = xNodelst.Item(0);
string adress = xNode.SelectSingleNode("formatted_address").InnerText;
string mahalle = xNode.SelectSingleNode("address_component[3]/long_name").InnerText;
string ilce = xNode.SelectSingleNode("address_component[4]/long_name").InnerText;
string il = xNode.SelectSingleNode("address_component[5]/long_name").InnerText;
so you can pull anydata for google maps.

Xpath selection of all attributes

I have the xml below in a c# class.
string xml =#"<?xml version='1.0' encoding='UTF-8'?>
<call method='importCube'>
<credentials login='sampleuser#company.com' password='my_pwd' instanceCode='INSTANCE1'/>
<importDataOptions version='Plan' allowParallel='false' moveBPtr='false'/>
I need to update the XML held within the node attributes i.e.
string xml =#"<?xml version='1.0' encoding='UTF-8'?>
<call method='importCube'>
<credentials login='testuser#test.com' password='userpassword' instanceCode='userinstance'/>
<importDataOptions version='Actual' allowParallel='true' moveBPtr='true'/>
I've written code to do this :
// instantiate XmlDocument and load XML from string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// get a list of nodes
XmlNodeList aNodes = doc.SelectNodes("/call/credentials");
// loop through all nodes
foreach (XmlNode aNode in aNodes)
{
// grab the attribute
XmlAttribute idLogin = aNode.Attributes["login"];
XmlAttribute idPass = aNode.Attributes["password"];
XmlAttribute idInstance = aNode.Attributes["instanceCode"];
idLogin.Value = "myemail.com";
idPass.Value = "passtest";
idInstance.Value = "TestInstance";
}
It works but the issue at the minute is that I have to repeat the whole code block for each node path i.e.
XmlNodeList aNodes = doc.SelectNodes("/call/importDataOptions");
....
There has to be a better way. Any ideas how I can rip through the attributes in 1 pass?
Maybe just using a cast to XmlElement could help you to reduce your code:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlElement credential in doc.SelectNodes("/call/credentials"))
{
credential.SetAttribute("login" , "myemail.com" );
credential.SetAttribute("password" , "passtest" );
credential.SetAttribute("instanceCode", "TestInstance");
}
Another option is to create an object structure which resembles your XML vocabulary and deserialize your input into that objects, but it seems overkill.
EDIT: Per your comment, you could go with:
foreach (XmlElement node in doc.SelectNodes("/call/*")) // it's case sensitive
{
switch(node.Name)
{
case "credentials":
node.SetAttribute("login" , "myemail.com" );
node.SetAttribute("password" , "passtest" );
node.SetAttribute("instanceCode", "TestInstance");
break;
case "importDataOptions":
// ...
break;
default:
throw new ArgumentOutOfRangeException("Unexpected node: "+node.Name);
}
}

Reading attribute of an XML file

I have this XML file, I can read all the the nodes
<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
<CTe xmlns="http://www.portalfiscal.inf.br/cte">
<infCte versao="1.04" ID="CTe3512110414557000014604"></infCte>
</CTe>
</cteProc>
I have tried reading this using C#
string chavecte;
string CaminhoDoArquivo = #"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo
chavecte = xmlDoc.SelectSingleNode("infCTe")
.Attributes.GetNamedItem("Id").ToString();
but something is wrong with this code.
If you want to use Linq To Xml
var xDoc = XDocument.Load(CaminhoDoArquivo);
XNamespace ns = "http://www.portalfiscal.inf.br/cte";
var chavecte = xDoc.Descendants(ns+"infCte").First().Attribute("id").Value;
PS: I am assuming your xml's invalid line is as
<infCte versao="1.04" id="CTe3512110414557000014604"></infCte>
replace
chavecte = xmlDoc.SelectSingleNode("infCTe").Attributes.GetNamedItem("Id").Value;
with
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ab", "http://www.portalfiscal.inf.br/cte");
chavecte = xmlDoc.SelectSingleNode("//ab:infCte", nsmgr)
.Attributes.GetNamedItem("Id").Value;
I've also noticed that infCte doesn't have the ID attribute properly defined in your xml
Another possible solution is:
string CaminhoDoArquivo = #"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo
// Select the node you're interested in
XmlNode node = xmlDoc.SelectSingleNode("/cteProc/CTe/infCte");
// Read the value of the attribute "ID" of that node
string chavecte = node.Attributes["ID"].Value;

Better way to convert a string to XmlNode in C#

I wanted to convert a string (which obviously is an xml) to an XmlNode in C#.While searching the net I got this code.I would like to know whether this is a good way to convert a string to XmlNode? I have to preform this conversion within a loop, so does it cause any performace issues?
XmlTextReader textReader = new XmlTextReader(new StringReader(xmlContent));
XmlDocument myXmlDocument = new XmlDocument();
XmlNode newNode = myXmlDocument.ReadNode(textReader);
Please reply,
Thanks
Alex
should be straight-forward:
string xmlContent = "<foo></foo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlContent);
XmlNode newNode = doc.DocumentElement;
or with LINQ if that's an option:
XElement newNode = XDocument.Parse(xmlContent).Root;
The accepted answer works only for single element. XmlNode can have multiple elements like string xmlContent = "<foo></foo><bar></bar>"; (Exception: "There are multiple root elements");
To load multiple elements use this:
string xmlContent = "<foo></foo><bar></bar>";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<singleroot>"+xmlContent+"</singleroot>");
XmlNode newNode = doc.SelectSingleNode("/singleroot");
XmlDocument Doc = new XmlDocument();
Doc.LoadXml(xml);

Categories