Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何读取XML节点值或名称c#_C#_Xml - Fatal编程技术网

如何读取XML节点值或名称c#

如何读取XML节点值或名称c#,c#,xml,C#,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> fo

我有下面的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>

foreach循环中“attributeValue”所需的输出应为“05-26-2016”/05-27-2016。有人能告诉我我遗漏了什么吗。

在您的
Xml
中没有名为
值的属性,这可能是您收到null的原因

a.GetAttribute("Value"); // Will return null. 
我建议,您可以使用
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");
        }
如果要对所有元素执行此操作,请使用
Where
子句

var matches = doc.Root.Elements("DateTime")
                      .Where(x=>x.Attribute("date").Value == attribute2.Value);

foreach(var match in matches)
{
    // logic here.
}

看看这个

您已经将xml包含作为字符串。但我给出的不是输入,而是xml路径。它正在给我根级别的错误数据无效。第1行,位置1。您的
xml
有问题,请尝试使用internet explorer或任何其他工具打开,您可以找出缺少的内容。Test1 Test2是否使用load方法提供文件名?检查我的更新答案。但当我在foreach循环中使用此选项时,当值与日期时间匹配时(如果(a.Attributes[“value”].value==attribute2.value)),则需要将其作为子项显示。如何比较和添加
var matches = doc.Root.Elements("DateTime")
                      .Where(x=>x.Attribute("date").Value == attribute2.Value);

foreach(var match in matches)
{
    // logic here.
}