i have below xml.
<Data>
<DateTime date="05-26-2016">
<Time time="09:53:46 AM">Test1</Time>
</DateTime>
<DateTime date="05-27-2016">
<Time time="09:54:56 AM">Test2</Time>
</DateTime>
</Data>
i use below code to get the DateTime Name/Value but it is giving null.
xmlDoc.Load(@"E:\testdoc.xml");
XmlElement rootNode = xmlDoc.DocumentElement;
foreach (XmlElement a in rootNode.ChildNodes)
{
var attributeValue = a.GetAttribute("Value");
if (a.Attributes["Value"].Value == attribute2.Value)
{
a.AppendChild(userChildNode2);
}
}
the required output for "attributeValue" should be "05-26-2016"/05-27-2016 in foreach loop. can some one let me know what i am missing.
In your Xml
there is no attribute with the name Value
, that could be a reason you are receiving null.
a.GetAttribute("Value"); // Will return null.
I suggest, you could use XDocument
and do this.
XDocument doc = XDocument.Load(filename);
var fmatch = doc.Root.Elements("DateTime")
.FirstOrDefault(x=>x.Attribute("date").Value == attribute2.Value);
if(fmatch!= null)
{
fmatch.Add(new XElement("child", "value")); // use details you would like to add as an element.
}
// add attribute in element use below
if (fmatch != null)
{
fmatch.Add( new XElement("Time", new XAttribute("time", DateTime.Now.ToString("hh:mm:ss tt")),"Test append in same date"));
doc.Save(@"E:\testdoc.xml");
}
if you want to do it for all elements use Where
clause
var matches = doc.Root.Elements("DateTime")
.Where(x=>x.Attribute("date").Value == attribute2.Value);
foreach(var match in matches)
{
// logic here.
}
Take a look at this Demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.