使用条件c#读取特定的xml节点

时间:2016-11-24 04:51:01

标签: c# xml

我想读取XML中的特定节点,就像任何“Log”(根节点)节点包含“Message”节点一样,它应该读取“Log”节点下的所有节点。

注意:Log节点是根节点,“log”节点下有许多节点。

例如:

<TestLogDataSet>

  <Log>
    <Assembly>TestCase</Assembly>
    <TestMethod>Application</TestMethod>
    <Status>Passed</Status>
    <Trace />
   </Log>


  <Log>
    <Assembly>TestCase</Assembly>
    <TestMethod>Application</TestMethod>
    <Status>Failed</Status>
    <Message>
  <pre><![CDATA[ Error while deleting the Project]]>
 </pre>
    </Message>
    <Trace />

  </Log>

</TestLogDataSet>

代码:

string xmlFile = File.ReadAllText(@"D:\demo.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlFile);
foreach (XmlNode lognode in xmlDoc.SelectNodes("/TestLogDataSet/Log[Message]"))
{
   foreach (XmlNode node in lognode.ChildNodes)
   {
       string n1 = node.InnerText;
       textBox1.Text = n1 + "\r\n";
   }
}

2 个答案:

答案 0 :(得分:1)

您可以使用XPath。

StringBuilder nodeText = new StringBuilder();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(<your xml here>);
foreach (XmlNode lognode in xmlDoc.SelectNodes("/TestLogDataSet/Log[Message]")) //select all log nodes with Message as child tag
{
    string status = lognode.SelectSingleNode("./Status").InnerText;
    if (!string.Equals(status,"failed",StringComparison.OrdinalIgnoreCase))
    {
       continue;
    }
    foreach (XmlNode node in lognode.ChildNodes)
    {
         nodeText.Append(node.LocalName);
         nodeText.Append(":");
         nodeText.Append(node.InnerText);//read inner text of node here
         nodeText.Append("\n");
    }
}
Console.WriteLine(nodeText.ToString());

答案 1 :(得分:0)

如果你想要Log节点,那么这应该足够了:

var nodes =
    xd
        .Root
        .Elements("Log")
        .Where(x => x.Element("Message") != null);

这给出了:

nodes #1

如果你想要一个所有子节点的列表(这是我从你的问题中理解你想要的,但它看起来有点奇怪),那么这有效:

var nodes =
    xd
        .Root
        .Elements("Log")
        .Where(x => x.Element("Message") != null)
        .SelectMany(x => x.Elements());

这给出了:

nodes #2