2016-11-24 73 views
-3

我想读取XML中的特定节点,就好像任何“Log”(根节点)节点包含“Message”节点,它应该读取“Log”节点下的所有节点。使用条件c读取特定的xml节点#

注意:日志节点是根节点,“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"; 
    } 
} 
+0

您的代码示例是不完整的。 –

+0

缺什么? – New

回答

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()); 
+0

如果我在xml中有多个Messages节点,它只取得xml的最后一个节点。 – New

+0

该代码将读取其中至少有一个消息节点的所有日志节点。除了我已经检查了我的结束,代码是读取每个日志节点内的所有消息节点 –

+0

好吧,那么你将如何打印LOG节点的所有d子节点在循环?这里我使用字符串n1 = node [“Status”]。InnerText;在第二个foreach循环中,但它显示错误消息。 – New

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