[英]how to read XML node value or name c#
i have below xml. 我有下面的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. 我使用下面的代码来获取DateTime名称/值,但它给出了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. 在foreach循环中,“ attributeValue”的必需输出应为“ 05-26-2016” / 05-27-2016。 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. 在您的
Xml
,没有名称为Value
属性,这可能是您收到null的原因。
a.GetAttribute("Value"); // Will return null.
I suggest, you could use XDocument
and do this. 我建议您可以使用
XDocument
并执行此操作。
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 如果要对所有元素执行此操作,请使用
Where
子句
var matches = doc.Root.Elements("DateTime")
.Where(x=>x.Attribute("date").Value == attribute2.Value);
foreach(var match in matches)
{
// logic here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.