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

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();
}

Related

Finding a set of nodes in an XML [duplicate]

Can't get any result in feeds.
feedXML has the correct data.
XDocument feedXML = XDocument.Load(#"http://search.twitter.com/search.atom?q=twitter");
var feeds = from entry in feedXML.Descendants("entry")
select new
{
PublicationDate = entry.Element("published").Value,
Title = entry.Element("title").Value
};
What am I missing?
You need to specify the namespace:
// This is the default namespace within the feed, as specified
// xmlns="..."
XNamespace ns = "http://www.w3.org/2005/Atom";
var feeds = from entry in feedXML.Descendants(ns + "entry")
...
Namespace handling is beautifully easy in LINQ to XML compared with everything other XML API I've ever used :)
You need to specify a namespace on both the Descendents and Element methods.
XDocument feedXML = XDocument.Load(#"http://search.twitter.com/search.atom?q=twitter");
XNamespace ns = "http://www.w3.org/2005/Atom";
var feeds = from entry in feedXML.Descendants(ns + "entry")
select new
{
PublicationDate = entry.Element(ns + "published").Value,
Title = entry.Element(ns + "title").Value
};
If you look at the XML returned by the HTTP request, you will see that it has an XML namespace defined:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" ...>
<id>tag:search.twitter.com,2005:search/twitter</id>
...
</feed>
XML is just like C#, if you use an element name with the wrong namespace, it is not considered to be the same element! You need to add the required namepsace to your query:
private static string AtomNamespace = "http://www.w3.org/2005/Atom";
public static XName Entry = XName.Get("entry", AtomNamespace);
public static XName Published = XName.Get("published", AtomNamespace);
public static XName Title = XName.Get("title", AtomNamespace);
var items = doc.Descendants(AtomConst.Entry)
.Select(entryElement => new FeedItemViewModel()
new {
Title = entryElement.Descendants(AtomConst.Title).Single().Value,
...
});
The issue is in feedXML.Descendants("entry"). This is returning 0 results
According to the documentation you need to put in a fully qualified XName

Deleting node from string with xml structure

I have an string parameter with xml content in it. Basically the string have an XML inside.
string S = funcThatReturnsXML (parameters);
S have the next text:
<?xml version="1.0" encoding="utf-8" ?>
<tagA>
<tagB>
<tagBB>
..
.
.
</tagBB>
.
.
</tagB>
<tagC>
..
..
.
</tagC>
</tagA>
The funcThatReturnsXML (parameters) creates an XmlDocument object but the return it as a string, I cant change this function, to much stuff works with it.
Tried to create XmlDocument objetc but the SelectSingleNode return null.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(S);
XmlNode root = xmlDoc.SelectSingleNode("tagB");
How can I delete from string S (not XML Object) specific node, for example <tagB>
EDIT: this is the XML I tested with:
<?xml version="1.0" ?>
- <Request xmlns:xsi="http://www.mysite.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <info xmlns="http://www.mysite.com">
<RequestTR>54</RequestTR>
<time>2013-12-22</time>
</info>
- <Parameters xmlns="http://www.mysite.com">
<id>3</id>
<name>2</name>
</Parameters>
<title>Request</title>
</Request>
Try this:
string S = funcThatReturnsXML(parameters);
var doc = XDocument.Parse(S);
var nodeToRemove = doc.Descendants("tagB");
nodeToRemove.Remove();
That will remove all nodes named "tagB" from string S which contains xml.
UPDATE 1:
Sorry, i missed to include one more line:
S = doc.ToString();
My first code above removed "tagB" from doc but didnt save it back to S variable.
UPDATE 2:
I tested with following xml which contain attribute:
<tagA attribute="value">
<tagB>
<tagBB>
</tagBB>
</tagB>
<tagC></tagC>
</tagA>
and the output of Console.WriteLine(S):
<tagA attribute="value">
<tagC></tagC>
</tagA>
UPDATE 3:
Given your updated xml format, I know why my previous code didn't work for you. That was because your xml have namespace (xmlns) declared. The solution is to use LocalName when searching for the node to be removed, that will search for node name while ignoring its namespace. The follwoing example shows how to remove all "info" node:
var doc = XDocument.Parse(S);
var nodeToRemove = doc.Descendants().Where(o => o.Name.LocalName == "info");
nodeToRemove.Remove();
S = doc.ToString();
If you can determine the particular outer element to remove from the returned XML, you could use LINQ to XML:
var returnedXml = funcThatReturnsXML(parameters);
var xmlElementToRemove = funcThatReturnsOuterElement(returnedXml);
var xelement = XElement.Load("XmlDoc.txt");
xelement.Elements().Where(e => e.Name == xmlElementToRemove).Remove();
For example:
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
// pretend this is the funThatReturnsXML return value
var returnedXml = "<tagB><tagBB></tagBB></tagB>";
// get the outer XML element name
var xmlElementToRemove = GetOuterXmlElement(returnedXml);
// load XML from where ever
var xelement = XElement.Load("XmlDoc.txt");
// remove the outer element and all subsequent elements
xelement.Elements().Where(e => e.Name == xmlElementToRemove).Remove();
}
static string GetOuterXmlElement(string xml)
{
var index = xml.IndexOf('>');
return xml.Substring(1, index - 1);
}
}
Note that the above is a "greedy" removal method, if there is more than once element with the name returned via the GetOuterXmlElemet method they will all be removed. If you want a specific instance to be removed then you will require something more sophisticated.
Building on your edit:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(S);
var nodeA = xmlDoc.SelectSingleNode("/tagA");
var nodeB = nodeA.SelectSingleNode("tagB");
nodeA.RemoveChild(nodeB);
To remove (possibly) multiple tagB nodes in unknown positions, you may try:
var bees = xmlDoc.SelectNodes("//tagB");
foreach (XmlNode bee in bees) {
var parent = bee.ParentNode;
parent.RemoveChild(bee);
}

How to read single node value from xml file

Hi i am trying to get value from xml but it shows node null.
Here is my xml file.
<?xml version="1.0" encoding="utf-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.cfhdocmail.com/TestAPI2/Result.xsd https://www.cfhdocmail.com/TestAPI2/Result.xsd" xmlns="https://www.cfhdocmail.com/TestAPI2/Result.xsd">
<data>
<key>MailingGUID</key>
<value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value>
</data>
<data>
<key>OrderRef</key>
<value>52186</value>
</data>
</result>
I want to get "MailingGUID" value.
Here is the code that i have tried:
private void readXML()
{
XmlDocument xml = new XmlDocument();
// You'll need to put the correct path to your xml file here
xml.Load(Server.MapPath("~/XmlFile11.xml"));
// Select a specific node
XmlNode node = xml.SelectSingleNode("result/data/value");
// Get its value
string name = node.InnerText;
}
Please tell me how i can get MailingGUID value.
Thanks
UPDATE:
I think there might be something wrong with your schemas, I removed references to them and your code worked fine. I tried this:
const string str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><result><data><key>MailingGUID</key><value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value></data><data><key>OrderRef</key><value>52186</value></data></result>";
var xml = new XmlDocument();
xml.LoadXml(str);
xml.DocumentElement.SelectSingleNode("/result/data/value").InnerText
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Parsing of xml is done here
Document doc = builder.parse(new File("C:\\Users\\User_Name\\Documents\\My Received Files\\PDSL_ABM.xml"));
//Here we get the root element of XML and print out
doc.getDocumentElement().normalize();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList list = doc.getElementsByTagName("MailingGUID");
int totalMailingGUID =list.getLength();
System.out.println("Total no of MailingGUID : " + totalSupplierPartID);
//Traversing all the elements from the list and printing out its data
for (int i = 0; i < list.getLength(); i++) {
//Getting one node from the list.
Node childNode = list.item(i);
System.out.println("MailingGUID : " + childNode.getTextContent());
}

How to parse a xml and read its values

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");

How to write CData in xml

i have an xml like :
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<entry_id></entry_id>
<entry_status></entry_status>
</entry>
i am writing data in it like:
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
xnode.InnerText = "<![CDATA[ " + Convert.ToString(sqlReader["story_status"]) + " ]]>" ;
but its change "<" to "&lt" of CDATA.
Please tell me how to fill values in above xml as a CData format.
i know that we can create CDATA like :
XmlNode itemDescription = doc.CreateElement("description");
XmlCDataSection cdata = doc.CreateCDataSection("<P>hello world</P>");
itemDescription.AppendChild(cdata);
item.AppendChild(itemDescription);
but my process is to read node of xml and change its value not to append in it.
Thanks
As described here: msdn
// Create an XmlCDataSection from your document
var cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));
// Append the cdata section to your node
xnode.AppendChild(cdata);
Do you really need it to be in CDATA, or do you just want to get the text in there in a way which won't require extra escaping in your code?
InnerText performs whatever escaping is required, so generally I'd just use
xnode.InnerText = Convert.ToString(sqlReader["story_status"]);
... but if you really want a CDATA node, you can create one yourself as per Nekresh's answer.
If you really need a CDATA section (see Jon's answer), you can achieve that like so:
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
XmlCDataSection cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));
xnode.InnerXml = cdata.OuterXml;
This will replace the contents of xnode, not append to it.
Use Node.InnerXml, not Node.InnerText. Node.InnerText is automatically replacing special values. Note that if you specify with CDATA in InnerXml, then Node.InnerText is text in CDATA.
Example:
public class Test
{
public static int Main(string[] args)
{
const string xmlTxt = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<entry>
<entry_id></entry_id>
<entry_status></entry_status>
</entry>";
TextReader treader = new StringReader(xmlTxt);
XmlReader xreader = XmlReader.Create(treader);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xreader);
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
//xnode.InnerText = "<![CDATA[something]]>";
xnode.InnerXml = "<![CDATA[something]]>";
Console.WriteLine("inner text is: " + xnode.InnerText);
xdoc.Save(Console.Out); Console.WriteLine();
return 0;
}
}
Program's output:
inner text is: something
<?xml version="1.0" encoding="ibm852"?>
<entry>
<entry_id>
</entry_id>
<entry_status><![CDATA[something]]></entry_status>
</entry>
XmlNode childNode = node.ChildNodes[0];
if (childNode is XmlCDataSection)
{
XmlCDataSection cdataSection = childNode as XmlCDataSection;
cdataSection.Value = newValue;
}
You can use writer.WriteCData(value);
where writer is XmlWriter object.

Categories