I have an xml file which contains an element .
i am storing the content of that xml file as string in csv in one of my projects.i am reading the content of that xml from csv and i want the data of the tag which exists in the content of xml file
I tried like this.
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");
but I am not getting the value of Mail into temp.what should i do?
GetElementsByTagName returns XmlNodeList. MSDN Reference
// Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i=0; i < elemList.Count; i++)
{
Console.WriteLine(elemList[i].InnerXml);
}
Linq solution:
var xDoc = XDocument.Load(dataRow["XML"].ToString());
var mailList = xDoc.Descendants("Mail")
.Select(x => new
{
MailID = x.Element("MailID").Value
})
.ToList();
UPDATE:
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");
// loop through all retrieved "Mail" elements
foreach(XmlElement xElem in temp)
{
string sMailText = xElem.InnerText;
}
Related
in this xml
<Roots>
<Root Name="cab">element_list</Root>
</Roots>
I want to get the value of attribute Name which is cab and element_list
I have this code
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Root Name=\"cab\">element_list</Root>");
XmlElement root = doc.DocumentElement;
var values = doc.Descendants("Roots").Select(x => new { Name = (string)x.Attribute("Name"), List = (string)x }).ToList();
What I get when I run the debugger is
values> Name = "null", List = "element_list"
I am not understanding why I am getting a null value when I should be getting cab for the attribute Name
XDocument is much easier to work with compared to XmlDocument. Perhaps consider switching to it?
public static void ParseXml()
{
string str = "<Roots><Root Name=\"cab\">element_list</Root></Roots>";
using TextReader textReader = new StringReader(str);
XDocument doc = XDocument.Load(textReader);
var val = doc.Element("Roots").Element("Root").Attribute("Name").Value;
}
I'm complete rookie I need to retrieve the value of last id in XML file here is
You can also use XPath within the Xml DOM like this :
string title;
XmlDocument xml = new XmlDocument();
xml.Load("~/purchases.xml");
// Or any other method to load your xml data in the XmlDocument.
// For example if your xml data are in a string, use the LoadXml method.
XmlElement elt = xml.SelectSingleNode("//SubMenu[#id='1']") as XmlElement;
if(elt!=null)
{
name=elt.GetAttribute("title");
}
Reference
As Jon suggested, you can use Linq To XML here.
XElement books = XElement.Load(filePath);
var lastId = books.Descendants("book").Select(x=>Int32.Parse(x.Attribute("ID").Value)).Last();
This will give you the last ID in the current list.You can now create your new Node
books.Add(new XElement("book",new XAttribute("ID",(lastId+1).ToString()),
new XAttribute("title","New Title"),
new XAttribute("price","1234")));
books.Save(filePath);
XmlDocument doc = new XmlDocument();
doc.Load("Yourxmlfilepath.xml");
//Display all the book titles.
XmlNodeList xNodeList = doc.SelectNodes("/bookstore/book");
foreach (XmlNode xNode in xNodeList)
{
var employeeName = xNode.OuterXml;
XmlDocument docnew = new XmlDocument();
docnew.LoadXml(employeeName);
foreach (XmlElement report in docnew.SelectNodes("book"))
{
string ID = report.GetAttribute("ID");
string title = report.GetAttribute("title");
string quantity = report.GetAttribute("quantity");
string price = report.GetAttribute("price");
}
}
From below imput xml, i should get output xml as described.
Input Xml
<BPSResponse> <Response> <Code>804</Code> <Text>TagID value is not genuine.</Text> </Response> </BPSResponse>
Output Xml
<BPSResponse><Response><Code>804</Code><Text>TagID value is not genuine.</Text></Response></BPSResponse>
I am creating xml by XElement.
var bpsResponseXml = new XElement("BPSResponse");
for (int i = 0; i < bpsResponseStatusCodes.Count; i++)
{
var bpsResponse = BPSResponseDictionary.GetBPSResponse(bpsResponseStatusCodes[i]);
bpsResponseXml.Add(new XElement("Response",
new XElement("Code", bpsResponse.Code),
new XElement("Text", bpsResponse.Text)));
}
var outPutXml = bpsResponseXml.Value;
I want output xml as formatted above.
var doc = new System.Xml.XmlDocument()
{
PreserveWhitespace = false
};
doc.LoadXml(xmlString);
string flat = doc.OuterXml;
I just have to disable the formatting while converting to string. Below is sample code.
var bpsResponseXml = new XElement("BPSResponse");
bpsResponseXml.Add(new XElement("Response",
new XElement("Code", "804"),
new XElement("Text", "TagID value is not genuine")));
var outPutXml = bpsResponseXml.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);
I am new to Xml, I have to Iterate into the tags(Loop into all Rack, all Servers, all Model Details, all Power supplies and display the sum of all quantity of all the Power supplies through Pop up message)
I am able to Load the Xml in C# like this:-
XmlDocument xworkload = new XmlDocument();
XmlDocument doc = new XmlDocument();
private void button1_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".xml"; // Default file extension
dlg.Filter = "Xml documents (.xml)|*.xml"; // Filter files by extension
var result = dlg.ShowDialog();
if (result == true)
{
xworkload.Load(dlg.FileName);
string xmlcontents = xworkload.InnerXml; // to get xml string, This is working
XmlNode xnd =xworkload.DocumentElement.SelectSingleNode("PowerSupply/quantity");
foreach(XmlNode _node in xnd)
{
String _nodeValue =_node.InnerText.ToString(); //This is not working
MessageBox.Show(_nodeValue.ToString());
}
}
}
How to display the Final sum of Power supply Quantity?
Here is correct XPath you should use:
XmlNode xnd = xworkload.SelectSingleNode("//PowerSupply/Item/quantity");
You had two problems:
quantity is not direct child of PowerSupply element - there is Item between them.
Also PowerSupply is not direct child of root element, so you need to use // to search anywhere in document.
Consider also using Linq to Xml for parsing xml. You still able to use XPath:
var xdoc = XDocument.Load(dlg.FileName);
int quantity = (int)xdoc.XPathSelectElement("//PowerSupply/Item/quantity");
That's it - you have integer quantity value in two lines.
EDIT: If you have many PowerSupply elements and you want to calculate sum of their quantities
int sum = xdoc.XPathSelectElements("//PowerSupply/Item/quantity")
.Sum(q => (int)q);
Or with your original approach:
XmlNodeList quantities = xworkload.SelectNodes("//PowerSupply/Item/quantity");
int sum = 0;
foreach (XmlNode quantity in quantities)
sum += Int32.Parse(quantity.InnerText);
You should be using .SelectNodes and an XmlNodeList. Also, the .DocumentElement part is extraneous and unnecessary, and there was an issue with your XPath.
There's also no need to call .ToString() on a string and then call it again on that string:
XmlNodeList xnd = xworkload.SelectNodes("//PowerSupply/Item/quantity");
foreach(XmlNode _node in xnd)
{
string _nodeValue =_node.InnerText;
MessageBox.Show(_nodeValue);
}
You could get the total quantity of power supplies like this:
XmlNodeList xnd = xworkload.SelectNodes("//PowerSupply/Item/quantity");
int powerSupplyCount = 0;
foreach(XmlNode _node in xnd)
{
int count;
if(int.TryParse(_node.InnerText, out count))
{
powerSupplyCount += count;
}
}
MessageBox.Show(powerSupplyCount.ToString());
I currently have the following code:
XPathNodeIterator theNodes = theNav.Select(theXPath.ToString());
while (theNodes.MoveNext())
{
//some attempts i though were close
//theNodes.RemoveChild(theNodes.Current.OuterXml);
//theNodes.Current.DeleteSelf();
}
I have set xpath to what I want to return in xml and I want to delete everything that is looped. I have tried a few ways of deleting the information but it does't like my syntax. I found an example on Microsoft support: http://support.microsoft.com/kb/317666 but I would like to use this while instead of a for each.
Any comments or questions are appreciated.
Why not to use XDocument?
var xmlText = "<Elements><Element1 /><Element2 /></Elements>";
var document = XDocument.Parse(xmlText);
var element = document.XPathSelectElement("Elements/Element1");
element.Remove();
var result = document.ToString();
result will be <Elements><Element2 /></Elements>.
Or:
var document = XDocument.Load(fileName);
var element = document.XPathSelectElement("Elements/Element1");
element.Remove();
document.Savel(fileName);
[Edit] For .NET 2, you can use XmlDocument:
XmlDocument document = new XmlDocument();
document.Load(fileName);
XmlNode node = document.SelectSingleNode("Elements/Element1");
node.ParentNode.RemoveChild(node);
document.Save(fileName);
[EDIT]
If you need to remove all child elements and attributes:
XmlNode node = document.SelectSingleNode("Elements");
node.RemoveAll();
If you need to keep attributes, but delete elements:
XmlNode node = document.SelectSingleNode("Elements");
foreach (XmlNode childNode in node.ChildNodes)
node.RemoveChild(childNode);
string nodeXPath = "your x path";
XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);
XmlNode node = document.SelectSingleNode(nodeXPath);
node.RemoveAll();
XmlNode parentnode = node.ParentNode;
parentnode.RemoveChild(node);
document.Save("File Path");
You can use XmlDocument:
string nodeXPath = "your x path";
XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);//or document.LoadXml(...
XmlNode node = document.SelectSingleNode(nodeXPath);
if (node.HasChildNodes)
{
//note that you can use node.RemoveAll(); it will remove all child nodes, but it will also remove all node' attributes.
for (int childNodeIndex = 0; childNodeIndex < node.ChildNodes.Count; childNodeIndex++)
{
node.RemoveChild(node.ChildNodes[childNodeIndex]);
}
}
document.Save("your file path"));