Xml parser doesn't work - c#

<?xml version="1.0" encoding="utf-8"?>
<response list="true">
<audio>
<aid>253663595</aid>
<artist>Example</artist>
<duration>389</duration>
<lyrics_id>57485771</lyrics_id>
<genre>18</genre>
</audio>
<audio>
<aid>253663595</aid>
<artist>Example1</artist>
<duration>400</duration>
<lyrics_id>57485772</lyrics_id>
<genre>20</genre>
</audio>
</response>
Source code
XmlDocument allAudio = new XmlDocument();
allAudio.Load(#"e:\Audio.xml");
StreamWriter write_text = File.CreateText(#"e:\Audio.txt");
XmlNodeList audioNodes = allAudio.GetElementsByTagName("audio");
foreach (XmlNode audioNode in audioNodes)
{
XmlNode artistNode = audioNode["artist"];
write_text.WriteLine(String.Format("{0}", artistNode.Value));
}
write_text.Close();
Hi, I can't parse xml. I want write some node values in file, but as result I get an empty txt file.

You want: artistNode.InnerText
Not: artistNode.value

Related

Remove an item from XML file using C#

I'm trying to write and remove items (categories) that I've stored in an XML file. I've figured out how to add using new XElement and doc.Root.Add but I don't know how to remove and item that has the same title as the input.
XML:
<?xml version="1.0" encoding="utf-8"?>
<categories>
<category title="Horror"></category>
<category title="Romance"></category>
<category title="Health"></category>
<category title="SciFi"></category>
<category title="Programming" />
<category title="History" />
</categories>
C#:
public static void RemoveFromCategoryXMLFile(string title)
{
XmlDocument doc = new XmlDocument();
doc.Load("../../DAL/XML_Categories/Categories.xml");
XmlNode node = doc.SelectSingleNode($"/categories/category[#name='{title}']");
if (node != null)
{
XmlNode parent = node.ParentNode;
parent.RemoveChild(node);
doc.Save("../../DAL/XML_Categories/Categories.xml");
}
}
I want the item that matches the string title to be removed from the document. Right now nothing happens and it seems like the XmlNode returns null.
Using XDocument is recommended, as it is a newer class for parsing XML. With such class it's enought to use such code:
var title = "Horror";
var xml = XDocument.Load(#"path to XML");
xml.Root.Elements("category").Where(e => e.Attribute("title").Value == title).Remove();
xml.Save(#"path to output XML");

Unable to use InsertAfter for XmlDocument in c#

Hi below are the XML files which is master XML
<?xml version="1.0" encoding="utf-16"?>
<Verify>
<ver>
<ECU>
<values>
</values>
</ECU>
</ver>
</Verify>
I have multiple files which are of same structure as below
<?xml version="1.0" encoding="utf-16"?>
<Verify>
<ver>
<ECU>
<values>
</values>
</ECU>
</ver>
</Verify>
I want my output as
<?xml version="1.0" encoding="utf-16"?>
<Verify>
<ver>
<ECU>
<values>
</values>
</ECU>
<ECU>
<values>
</values>
</ECU>
<ECU>
<values>
</values>
</ECU>
</ver>
</Verify>
I am using below code to read first one as master xml
and other files from xmls folder. I want to add ECU node from these files under ECU node of master file.
XmlDocument xmlMaster = new XmlDocument();
xmlMaster.Load(#"C:\MasterXMLFile.xml");
XmlElement masterRoot = xmlMaster.DocumentElement;
XmlNode masterParent = masterRoot.LastChild.LastChild;
var downloadfolder = #"C:\AllXMLs\xmls\";
string[] files = Directory.GetFiles(downloadfolder);
foreach (var xx in files)
{
XmlNode masterNode = masterRoot.LastChild.LastChild;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xx);
XmlElement root = xdoc.DocumentElement;
XmlElement tempNode = (XmlElement)root.LastChild.LastChild;
masterRoot.InsertAfter(tempNode, masterRoot.SelectSingleNode("//ECU").ParentNode);
}
xmlMaster.Save(#"C:\mergeg.xml");
I am getting error at InsertAfter statement as Object reference not set to an instance of an object.
Please suggest me any solution.
Your tempNode is from xdoc document context. You should import it to xmlMaster document context:
XmlNode importedECU = xmlMaster.ImportNode(tempNode, true);
Also instead of InsertAfter it's better to use AppendChild and append new ECU nodes as children of master ver element:
var masterVer = masterRoot.SelectSingleNode("//ver");
foreach(var file in files)
{
var xdoc = new XmlDocument();
xdoc.Load(file);
var tempNode = xdoc.DocumentElement.LastChild.LastChild;
var importedECU = xmlMaster.ImportNode(tempNode, true);
masterVer.AppendChild(importedECU);
}
Your InsertAfter should be on the parentNode of the node you want to insert after, so the parent of tempNode.

Get specific values from Xml

I don't how to extract the values from XML document, and am looking for some help as I'm new to C#
I am using XmlDocument and then XmlNodeList for fetching the particular XML document
Here is my code
XmlNodeList XMLList = doc.SelectNodes("/response/result/doc");
And my XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>
<doc>
<long name="LoadID">494</long>
<long name="EventID">5557</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
<doc>
<long name="LoadID">774</long>
<long name="EventID">5558</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
</result>
</response>
In this i have to fetch every the XMLData data that is under every doc tag and i have to fetch last doc tag EventID.
var xml = XDocument.Parse(xmlString);
var docs = xml.Root.Elements("doc");
var lastDocEventID = docs.Last()
.Elements("long")
.First(l => (string)l.Attribute("name") == "EventID")
.Value;
Console.WriteLine ("Last doc EventId: " +lastDocEventID);
foreach (var doc in docs)
{
Console.WriteLine (doc.Element("str").Element("TransactionDate").Value);
}
prints:
Last doc EventId: 5558
2014-05-28T14:17:31.2186777-06:00
2014-05-28T14:17:31.2186777-06:00
You can use two XPath expressions to select the nodes you want. To answer each part of your question in turn:
To select all of the XMLData nodes:
XmlNodeList XMLList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
To select the last EventId:
XmlNode lastEventIdNode =
doc.SelectSingleNode("/response/result/doc[position() =
last()]/long[#name='EventID']");
If not all doc nodes are guaranteed to have an event id child node, then you can simply:
XmlNodeList eventIdNodes =
doc.SelectNodes("/response/result/doc[long[#name='EventID']]");
XmlNode lastNode = eventIdNodes[eventIdNodes.Count - 1];
That should give you what you've asked for.
Update;
If you want the XML data inside each strXml element, you can use the InnerXml property:
XmlNodeList xmlList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
foreach(XmlNode xmlStrNode in xmlList)
{
string xmlInner = xmlStrNode.InnerXml;
}
There's one result tag short in your xml.
Try using this. It's cleaner too imho
XmlNodeList docs = doc.SelectSingleNode("response").SelectSingleNode("result").SelectNodes("doc");
Then you can use a combination of SelectSingleNode, InnerText, Value to get the data from each XmlNode in your list.
For example if you want the EventID from the first doc tag:
int eventID = int.Parse(docs[0].SelectSingleNode("long[#name='EventID']").InnerText);

Get entire XML except root element

<Employees>
<Product_Name>
<hello1>product1</hello1>
<hello2>product2</hello2>
<hello3>product3</hello3>
<hello4>product4</hello4>
</Product_Name>
<product_Price>
<hello1>111</hello1>
<hello2>222</hello2>
<hello3>333</hello3>
<hello4>444</hello4>
</product_Price>
</Employees>
is it possible to convert the following XML to the XML shown below using C#. I tried using remove function but it didn't work. I also tried to get the value of root node. Didn't work
<Product_Name>
<hello1>product1</hello1>
<hello2>product2</hello2>
<hello3>product3</hello3>
<hello4>product4</hello4>
</Product_Name>
<product_Price>
<hello1>111</hello1>
<hello2>222</hello2>
<hello3>333</hello3>
<hello4>444</hello4>
</product_Price>
If you just want to fetch the inner xml,you can use the XmlReader's ReadInnerXml.The innerXML is fetched as a string(skipping the root node).
var xmlReader = XElement.Load("data.xml").CreateReader();
xmlReader.MoveToContent();
string innerXml = xmlReader.ReadInnerXml();
If you have access to Linq to XML, you should you XDocument.
caveat: I believe your xml is malformed - you should have something like:
<?xml version="1.0" encoding="utf-8"?>
Add the first xml tag to the xml.
string xml = #"<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Product_Name>
<hello1>product1</hello1>
<hello2>product2</hello2>
<hello3>product3</hello3>
<hello4>product4</hello4>
</Product_Name>
<product_Price>
<hello1>111</hello1>
<hello2>222</hello2>
<hello3>333</hello3>
<hello4>444</hello4>
</product_Price>
</Employees>";
XDocument xDoc = XDocument.Parse(xml);
// get the elements
var rootElements = xDoc.Root.Elements();
Alternatively, you can load the xml from a file:
XDocument xDoc = XDocument.Load("xmlFile.xml");
You can store it as XmlNodeList to be well-formed. Here's a working example of how to do it:
XmlDocument xml= new XmlDocument();
xml.LoadXml(#"<Employees>
<Product_Name>
<hello1>product1</hello1>
<hello2>product2</hello2>
<hello3>product3</hello3>
<hello4>product4</hello4>
</Product_Name>
<product_Price>
<hello1>111</hello1>
<hello2>222</hello2>
<hello3>333</hello3>
<hello4>444</hello4>
</product_Price>
</Employees>");
var nodeList = xml.SelectNodes("Employees");
foreach (XmlNode node in nodeList)
{
Console.WriteLine(node.InnerXml); //this will give you your desired result
}

How do I modify node value while iterating with XPathNodeIterator?

I'm navigating XML document with XPathNodeIterator, and I want to change some nodes' values.
I can't figure out how :(
Here's the code I'm using:
XPathDocument docNav = new XPathDocument(path);
XPathNavigator nav = docNav.CreateNavigator();
nav.MoveToRoot();
XPathNodeIterator itemsIterator = nav.Select("/foo/bar/item");
while (mediumsIterator.MoveNext())
{
XPathNodeIterator subitemsIterator = itemsIterator.Current.Select("SubitemsList/name");
while (subitemsIterator.MoveNext())
{
XPathNodeIterator nodesIterator = itemsIterator.Current.Select("Param");
nodesIterator.MoveNext();
String the_params = nodesIterator.Current.Value;
// check if I need to modify nodesIterator.Current.Value
// ...
// ok I do - how?
}
}
And the XML file sample:
<?xml version="1.0" encoding="utf-8"?>
<foo>
<bar>
<item>
<Param />
<SubitemsList>
<name>name one</name>
<name>name two</name>
...
</SubitemsList>
</item>
...
</bar>
</foo>
Or maybe there's a better way to do this?
I found a way:
Replace XPathDocument with XmlDocument
When I get to the needed node
...
XmlNode node = ((IHasXmlNode)nodesIterator.Current).GetNode();
node.InnerText = "new text";

Categories

Resources