如何在C#控制台应用中读取XML文件并识别输出带错误属性的Page节点
Solution for Identifying Error Page Nodes in XML
Hey Tiago, great job getting the basic XML reading logic working! To add the error detection you need, we just need to check each <Page> node for the presence of ErrorCode and ErrorMessage attributes as we iterate through them. Here's how you can update your code:
using System; using System.Xml; using System.IO; namespace XmlReaderConsoleAPP { class Program { static void Main() { XmlDocument xml = new XmlDocument(); try { xml.Load("c:\\SaintGobain_Pam_20210118 .xml"); } catch(Exception ex) { Console.WriteLine("Error: {0}", ex.Message); return; } XmlNodeList xnLista = xml.SelectNodes(@"//Pages/Page"); Console.WriteLine($"Selected {xnLista.Count} nodes"); int i = 0; foreach (XmlNode xn in xnLista) { i++; // Check if the Page node contains error attributes if (xn.Attributes["ErrorCode"] != null) { // Highlight error in red for immediate visibility Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{i} {xn.Name}: {xn.Attributes["ImportFileName"].Value}"); Console.WriteLine($"* ERROR DETECTED * Code: {xn.Attributes["ErrorCode"].Value}, Message: {xn.Attributes["ErrorMessage"].Value}"); // Reset console color to default for subsequent output Console.ResetColor(); } else { Console.WriteLine($"{i} {xn.Name}: {xn.Attributes["ImportFileName"].Value}"); } } XmlNodeList xnLista2 = xml.SelectNodes(@"//IndexFields/IndexField"); Console.WriteLine($"Selected {xnLista2.Count} nodes"); foreach (XmlNode xn in xnLista2) { Console.WriteLine($"{++i} {xn.Name}: {xn.Attributes["Value"].Value}"); } } } }
Key Changes Explained:
- Added a check
xn.Attributes["ErrorCode"] != nullto detect if a Page node has error metadata - When an error is found, we switch the console text color to red (you can tweak this to another color if you prefer) to make the error stand out
- We display both the
ErrorCodeandErrorMessagevalues with a clear* ERROR DETECTED *label for clarity - After showing the error, we reset the console color to ensure normal output resumes
- Kept your original node counting and IndexField display logic fully intact
How It Works:
When you run the updated code:
- It loads the XML file exactly as before
- For each Page node:
- Normal nodes get the standard output line you had originally
- Nodes with error attributes get their file name printed, followed by a prominent error message in red
- It continues to display all IndexField values just like your original code
This way, any problematic Page nodes will be immediately noticeable in the console, while all other content remains unchanged.
内容的提问来源于stack exchange,提问作者Tiago Silva
相关产品推荐
相关产品推荐

