I've this xml :
<?xml version="1.0"?>
<channel>
<item>
<title>Le joyeux médecin</title>
<description>
<p>test blague description</p>
</description>
<pubDate>Dimanche, 02/03/2014</pubDate>
</item>
</channel>
And the code to parse the xml :
private void Feed(object Sender, DownloadStringCompletedEventArgs e)
{
XElement _xml;
try
{
if (!e.Cancelled)
{
_xml = XElement.Parse(e.Result);
Results.Items.Clear();
foreach (XElement value in _xml.Elements("channel").Elements("item"))
{
_item = new Flux();
_item.Title = value.Element("title").Value;
_item.Description = Regex.Replace(value.Element("description").Value,
#"<(.|\n)*?>", String.Empty);
Results.Items.Add(_item);
break;
}
}
}
catch
{
MessageBox.Show(e.Error.Message);
}
}
_xml contains the xml but the code into the foreach doesn't execute and I don't know why... thanks for any help !
Change your loop as:
foreach (XElement value in _xml.Elements("item"))
{
}
Since _xml is already channel
Related
I'm trying to load data from the nodes in my xml file to get them to post in a listbox.
Here is what my xml file looks like.
<?xml version="1.0" encoding="utf-8"?>
<MovieData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Movie>
<Name>Death Race</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
</Movie>
<Movie>
<Name>Death Race 2</Name>
<Type>Action</Type>
<Type>Adventure</Type>
<Rating>R</Rating>
<Disk>Blu-Ray</Disk>
</Movie>
</MovieData>
Here is what i am trying to do.
try
{
XmlDocument doc = new XmlDocument();
doc.Load(movieListXML);
XmlNodeList nodeList = doc.SelectNodes("/MovieData");
foreach (XmlNode xn in nodeList)
{
XmlNode movie = xn.SelectSingleNode("Movie");
if (movie != null)
{
movieTypeListBox.Items.Add(movie["Name"].InnerText);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Can anyone tell me where my problem is ? thanks.
iterate over your Movies not your MovieData
try
{
XmlDocument doc = new XmlDocument();
doc.Load("XMLFile1.xml");
XmlNode node = doc.SelectSingleNode("/MovieData");
foreach (XmlNode movie in node.SelectNodes("Movie"))
{
if (movie != null)
{
movieTypeListBox.Items.Add(movie["Name"].InnerText);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I want to modify XML data given below:
<?xml version="1.0" encoding="utf-8"?>
<allitems>
<item ID="17997" quantity="three">
<available>Y</available>
<last_modified_price>300</last_modified_price>
<edition>2008<edition>
<item>
<item ID="18039" quantity="two">
<available>Y</available>
<last_modified_price>250</last_modified_price>
<edition>2010<edition>
<item>
</allitems>
all elements value should be modified as per set in runtime....
For this I used following code but data is not modified..please help me in getting solution.
XmlDocument modifydoc = new XmlDocument();
modifydoc.Load(#"E:\XMLapp\XMLstorageWEB\patrick\XMLFile1.xml");
var root = modifydoc.GetElementsByTagName("allitems")[0];
var oldelem = root.SelectSingleNode("item[#ID =" + txt_id.Text + "]");
var newelem = modifydoc.CreateElement("item");
root.ReplaceChild(newelem, oldelem);
while (oldelem.ChildNodes.Count != 0)
{
XmlElement available= modifydoc.CreateElement("available");
available.InnerText = ddl_available.SelectedItem.Text;
XmlElement last_modified_price= modifydoc.CreateElement("last_modified_price");
last_modified_price.InnerText = ddl_last_modified_price.SelectedItem.Text;
XmlElement edition= modifydoc.CreateElement("edition");
edition.InnerText = ddl_edition.SelectedItem.Text;
newelem.AppendChild(available);
newelem.AppendChild(last_modified_price);
newelem.AppendChild(edition);
modifydoc.DocumentElement.AppendChild(newelem);
}
while (oldelem.Attributes.Count != 0)
{
newelem.Attributes.Append(oldelem.Attributes[0]);
}
modifydoc.Save(#"E:\XMLapp\XMLstorageWEB\patrick\XMLFile1.xml");
please give me solution..
Not the cleanest way, to add and remove a XmlNode, but just fixing your code I think this is what you want
var txt_id = "17997";
XmlDocument modifydoc = new XmlDocument();
modifydoc.Load(#"c:\temp\so\1.xml");
var root = modifydoc.GetElementsByTagName("allitems")[0];
var oldelem = root.SelectSingleNode("item[#ID =" + txt_id + "]");
var newelem = modifydoc.CreateElement("item");
root.ReplaceChild(newelem, oldelem);
XmlElement available= modifydoc.CreateElement("available");
available.InnerText = "CambiameInnerText";
XmlElement last_modified_price= modifydoc.CreateElement("last_modified_price");
last_modified_price.InnerText = "LastModifed";
XmlElement edition= modifydoc.CreateElement("edition");
edition.InnerText = "SelectedItem";
newelem.AppendChild(available);
newelem.AppendChild(last_modified_price);
newelem.AppendChild(edition);
modifydoc.DocumentElement.AppendChild(newelem);
foreach (XmlAttribute attribute in oldelem.Attributes)
{
newelem.SetAttribute(attribute.Name, attribute.Value);
}
and your xml is not correct, at least the example
<?xml version="1.0" encoding="utf-8"?>
<allitems>
<item ID="17997" quantity="three">
<available>Y</available>
<last_modified_price>300</last_modified_price>
<edition>2008</edition>
</item>
<item ID="18039" quantity="two">
<available>Y</available>
<last_modified_price>250</last_modified_price>
<edition>2010</edition>
</item>
</allitems>
Here is the small and easy example , i use for change the connectionString value in my [web.config]. I hope it's can help you. So easy to adapt for your code ;-)
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load("myFullPathWebConfig.xml");
foreach (System.Xml.XmlNode node in myXmlDocument["configuration"]["connectionStrings"])
{
if (node.Name == "add")
{
if (node.Attributes.GetNamedItem("name").Value == "SCI2ConnectionString")
{
node.Attributes.GetNamedItem("connectionString").Value = connectionString;
}
}
}
I am trying to query an xml document, but this code doesn't read xml parts with closed tag notation but reads fine xelement. Can anyone spot what I'm doing wrong?
I have program generated XML document which gives closed tagged file hence its an issue now..
<?xml version="1.0" encoding="utf-8" ?>
<Student>
<Person name="John" city="Auckland" country="NZ" />
<Person>
<Course>GDICT-CN</Course>
<Level>7</Level>
<Credit>120</Credit>
<Date>129971035565221298</Date>
</Person>
<Person>
<Course>GDICT-CN</Course>
<Level>7</Level>
<Credit>120</Credit>
<Date>129971036040828501</Date>
</Person>
</Student>
class Program
{
static void Main(string[] args)
{
XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");
IEnumerable<XElement> rows = from row in xDoc.Descendants("Person") select row;
foreach(XElement xEle in rows)
{
IEnumerable<XAttribute>attlist = from att in xEle.DescendantsAndSelf().Attributes() select att;
foreach(XAttribute xatt in attlist)
{
Console.WriteLine(xatt);
}
Console.WriteLine("-------------------------------------------");
}
Console.ReadLine();
}
}
Since you have added Course and other attributes as XElement, so you need to loop on XElements instead of attributes -
foreach (XElement xEle in rows)
{
IEnumerable<XAttribute> attlist = from att in xEle.DescendantsAndSelf()
.Attributes() select att;
foreach (XAttribute xatt in attlist)
{
Console.WriteLine(xatt);
}
foreach (XElement elemnt in xEle.Descendants())
{
Console.WriteLine(elemnt.Value);
}
Console.WriteLine("-------------------------------------------");
}
First you must navigate to Person level and iterate through Persons, then for each Person you can iterate through its attributes.
private static void Main(string[] args)
{
//string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//XDocument xDoc = XDocument.Load(path + "\\Student Data\\data.xml");
XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");
IEnumerable<XElement> xElements = xDoc.Descendants("Person");
foreach (XElement element in xElements)
{
foreach (XAttribute attribute in element.Attributes())
{
Console.WriteLine(attribute);
}
Console.WriteLine("-------------------------------------------");
}
Console.ReadLine();
}
I am New To C# I have problem...
I want to delete selected node from My XMl File
Here I just tried with this code but I didn't get please can any one help in that
private void btnDelete_Click(object sender, EventArgs e)
{
xdoc.Load(strFilename);
string Xpath = string.Format("root/{0}/{1}",_strProCat,_strProdType);
xdoc.SelectSingleNode(Xpath).RemoveAll();
xdoc.Save(strFilename);
MessageBox.Show("Deleted Successfully");
}
Here My Xml File
<root>
<product category="Soaps">
<product type="Washing">
<product name="Rin">
<Id>100</Id>
<AvailProducts>30</AvailProducts>
<Cost>20.00</Cost>
</product>
<product name="Tide">
<Id>101</Id>
<AvailProducts>30</AvailProducts>
<Cost>15.00</Cost>
</product>
</product>
</product>
</root>
Just I want to delete Node which product name="Tide"
You can simple use the below code:
private void btnDelete_Click(object sender, EventArgs e)
{
var xDoc = XDocument.Load(strFilename);
foreach (var elem in xDoc.Document.Descendants("product"))
{
foreach (var attr in elem.Attributes("name"))
{
if (attr.Value.Equals("Tide"))
elem.RemoveAll();
}
}
xDoc.Save(destinationFilename);
MessageBox.Show("Deleted Successfully");
}
Happy Coding...
Something like this should do it:
xdoc.Elements("product").Where(x=> x.Element("name").Value == "Tide").FirstOrDefault().Remove();
If you want XPath with XmlDocument then following is the way to do it..
XmlDocument xdoc = new XmlDocument();
xdoc.Load(strFilename);
string Xpath = string.Format("root/product[#category='{0}']/product[#type='{1}']/product[#name='{2}']", "Soaps", "Washing", "Tide");
xdoc.SelectSingleNode(Xpath).RemoveAll();
xdoc.Save(strFilename);
Update
As per your Requirement To Remove the empty node, try following code to remove empty node as
XmlNodeList emptyElements = xdoc.SelectNodes(#"//*[not(node())]");
for (int i = emptyElements.Count - 1; i > -1; i--)
{
XmlNode nodeToBeRemoved = emptyElements[i];
nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}
Now your final full flesh code will look like as
string Xpath = string.Format("root/product[#category='{0}']/product[#type='{1}']/product[#name='{2}']", "Soaps", "Washing", "Tide");
xdoc.SelectSingleNode(Xpath).RemoveAll();
XmlNodeList emptyElements = xdoc.SelectNodes(#"//*[not(node())]");
for (int i = emptyElements.Count - 1; i > -1; i--)
{
XmlNode nodeToBeRemoved = emptyElements[i];
nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}
xdoc.Save(strFilename);
I Have XML like
<rss>
<channel>
<item>
<category domain="category" nicename="change"><![CDATA[Changing Lives]]></category>
<category domain="category" nicename="events"><![CDATA[Events]]></category>
<category domain="category" nicename="leadership"><![CDATA[Leadership]]></category>
<category domain="category" nicename="spiritual-transformation"><![CDATA[Spiritual Transformation]]></category>
</item>
<item></item>
<item></item>
</channel>
</rss>
I am trying to read category innertext(changing lives, Events, Leadership) ... using foreach condition.. but for every loop I am getting Changing Lives only.. here is my code
protected void btnImportPost_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
string strPath = Server.MapPath("~/App_Data/willowcreekassociationblog.wordpress.xml");
doc.Load(strPath);
//Get Channel Node
XmlNode channelNode = doc.SelectSingleNode("rss/channel");
if (channelNode != null)
{
DateTime temp;
//Add NameSpace
XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
nameSpace.AddNamespace("excerpt", "http://wordpress.org/export/1.2/excerpt/");
nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
nameSpace.AddNamespace("wfw", "http://wellformedweb.org/CommentAPI/");
nameSpace.AddNamespace("wp", "http://wordpress.org/export/1.2/");
//Parse each item
foreach (XmlNode itemNode in channelNode.SelectNodes("item"))
{
//some code here
foreach (XmlNode categoryNode in itemNode.SelectNodes("category"))
{
//CMS.SiteProvider.CategoryInfo GetCate = null;
string CategoryName = itemNode.SelectSingleNode("category").InnerText;
Response.Write(#"<script language='javascript'>alert('root Document:" + CategoryName + "');</script>");
}
}
}
}
Just use
string CategoryName = categoryNode.InnerText;
The reason is that you are not writing out the InnerText of itemNode each time round the loop, instead, you are using SelectSingleNode to pull out the first match only.
Try changing your inner loop to:
foreach (XmlNode categoryNode in itemNode.SelectNodes("category"))
{
//CMS.SiteProvider.CategoryInfo GetCate = null;
//string CategoryName = itemNode.SelectSingleNode("category").InnerText; // incorrect
string CategoryName = categoryNode.InnerText;
Console.Write(CategoryName);
}