How to parse a xml and read its values - c#

i am using C# windows phone 8 and I have the following XML
<?xml version="1.0" encoding="UTF-8" ?>
<login res="SUCCESS" encstatus="DEFAULT" usedquota="0" />
I need to extract the values of res, encstatus and usedQuota.
How do I do that in xml parsing?
I tried this
XDocument xDoc = XDocument.Parse(str);
var pol = xDoc.Element("res");
var items = xDoc.Descendants("res");
Where str is the xml file, but all the elements are empty / null.

You're trying to get the attribute values, no element:
XDocument xDoc = XDocument.Parse(str);
var pol = (string)xDoc.Root.Attribute("res");

Those nodes are attributes:
XDocument xDoc = XDocument.Parse(str)
XElement login = xDoc.Root;
string res = (string)login.Attribute("res");
string encstatus = (string)login.Attribute("encstatus");
int usedquota = (int)login.Attribute("usedquota");

Related

c# get values from xml response

I am trying to get values from xml respone :
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://adaddaasd.com">
<A>14</A>
<B>Failed</B>
<C>22</C>
</Response>
My code is :
string responseString = await response.Content.ReadAsStringAsync();
var xDocument = XDocument.Parse(responseString);
var responseNode = xDocument.XPathSelectElement("/Response");
var A = xDocument.XPathSelectElement("/Response/A");
But I am getting null values for A and responseNode. Whats wrong? Thanks
You're blatantly ignoring the XML namespace that's defined in your XML document:
<Response xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns='http://adaddaasd.com'>
****************************
You need to include that into your querying - I would try to do it like this:
var xDocument = XDocument.Parse(responseString);
// *define* your XML namespace!
XNamespace ns = "http://adaddaasd.com";
// get all the <Response> nodes under the root with that XML namespace
var responseNode = xDocument.Descendants(ns + "Response");
// from the first <Response> node - get the descendant <A> nodes
var A = responseNode.FirstOrDefault()?.Descendants(ns + "A");
If you insist on using the XPathSelectElement method, then you must define an XmlNamespaceManager and use it in your XPath select:
// define your XML namespaces
XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(new NameTable());
xmlnsmgr.AddNamespace("ns", "http://adaddaasd.com");
// use the defined XML namespace prefix in your XPath select
var A = xDocument.XPathSelectElement("/ns:Response/ns:A", xmlnsmgr);

How to get the value of root element (without .Net 4)

How can we read the attribute value of root element of xml? I am using the following code
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE article PUBLIC "-//NPGSJ//DTD full length article DTD version
[
<!ENTITY xobx1 SYSTEM "abcx1.pdf" NDATA pdf>
]
<article id="abc" type="a">
<fm>
</fm>
<article>
I need to read this xml file and want to store the attribute value of article tag in some string to check the category of an article .
Please guide
You can try Something like this :
//You can replace "C:" with your specified path
XDocument xdoc = XDocument.Load(#"C:\yourxmlfilename.xml");
var root_attribure1 = xdoc.Root.Attribute("id").Value;
var root_attribure2 = xdoc.Root.Attribute("type").Value;
It works.
var x = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
"<article id=\"abc\" type=\"a\">"+
"<fm>"+
"</fm>"+
"</article>";
var doc = new XmlDocument();
doc.LoadXml(x);
var id = doc.SelectSingleNode("/article/#id").Value;
var type = doc.SelectSingleNode("/article/#type").Value;
I have found the solution.
static void Main(string[] args)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\Temp\emi20154a.xml");
string root_attribure1 = xdoc.DocumentElement.Attributes[0].Value;
string root_attribure2 = xdoc.DocumentElement.Attributes[1].Value;
Console.WriteLine("root_attribure1" + root_attribure1);
Console.WriteLine("root_attribure2" + root_attribure2);
Console.ReadLine();
}

How to get the values of all the elements in an XML into an array?

For example :
I have the following XML,
<?xml version="1.0" encoding="utf-8"?>
<TEST>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</Test>
I would like to get the values from the tags "SyncByte", "SOM", "PADD" and "LENLSB" into a single array. Is there an option within XML to accomplish this?
P.S. There are close to 20+ tags in the XML and not all tags contain values all the time. Hence if there is a single command to get all the values of the XML, then it would be great.
With Linq to Xml:
var xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Test>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</Test>";
var doc = XDocument.Parse(xml);
string[] values = doc.Root.Descendants().Select(x => x.Value).ToArray();
First:
your xml formate is wrong , it should be:
<?xml version="1.0" encoding="utf-8"?>
<TEST>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</TEST> <!--END Tag should same as TEST -->
Then you can query them like this:
var xml=XDocument.Load("d:\\test.xml");
var list=xml.Descendants("TEST")
.Select(x=>new
{
SyncByte=x.Element("SyncByte")==null?"":x.Element("SyncByte").Value,
SOM=x.Element("SOM")==null?"":x.Element("SOM").Value,
LENLSB=x.Element("LENLSB")==null?"":x.Element("LENLSB").Value
});
You can get the child of any parent node through 'XmlElement.ChildNodes' and store it in collection.
for eg :
static int Main(string[] args)
{
string strFilename = "Input.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
XmlElement elm = xmlDoc.DocumentElement;
XmlNodeList lstVideos = elm.ChildNodes;
for (int i = 0; i < lstVideos.Count; i++)
Console.WriteLine("{0}",lstVideos[i].InnerText );
}
else
Console.WriteLine("The file {0} could not be located",
strFilename);
Console.WriteLine();
return 0;
}

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;

Delete a whole Node from an Xml Advertisement file?

I am trying to delete a whole XmlNode which matches a certain condition
The format of my xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<Advertisements>
<Ad>
<ImageUrl>image/Hydrangeas.jpg</ImageUrl>
<NavigateUrl>www.google.com</NavigateUrl>
<AlternateText>nbfndbf</AlternateText>
<ID>0</ID>
<Impressions>1</Impressions>
</Ad>
</Advertisements>
My deleting code:
XElement x =
new XElement("Ad",
new XElement("ImageUrl", lblImageURL.Text),
new XElement("NavigateUrl", lblImageURL.Text),
new XElement("AlternateText", lblAlternateText.Text),
new XElement("ID", lblID.Text),
new XElement("Impressions", lblfrequency.Text));
string filepath = Request.PhysicalApplicationPath.ToString() + "Adrotator.xml";
XmlDocument xD = new XmlDocument();
xD.LoadXml(x.ToString());
XmlNode xN = xD.FirstChild;
xN.ParentNode.RemoveChild(xN);
**xD.Save(filepath);**
I am getting an error Invalid XML document. The document does not have a root element.
You can use linq to xml to achieve this here exmple how to remove node where value ID = 0
var q = (from c in doc.Descendants("Advertisements")
from v in c.Elements("Ad")
where (int) v.Element("ID") == 0
select v).Remove();
here is another example using xpath
doc.XPathSelectElement("Advertisements/Ad[ID = 0]").Remove();
You create a new XDocument (doc) with the following code:
XDocument doc = XDocument.Load(filepath);
Is there something in the Xml file (with a root element)? Also, you don't seem to use doc in the code, so it's at least not required.

Categories