我正在編寫一個C#類,用於生成電子郵件列表以在進程成功或失敗時使用。在通過Web上的XmlReader示例運行時,我發現驗證Read()比看起來更加困難。XmlReader測試返回換行符的字符串
我可以使用string.IsNullOrEmpty(x)來測試空值或空節點,但它仍然會通過該測試吹在x的工具提示中顯示「\ n」。測試「\ n」,「\ n」,「\ n」。 「\ n」或char(13)全部失敗。如果我使用x.Contains((char)13),它總是找到它並進入試圖構建電子郵件地址列表的代碼。到目前爲止,它總是失敗或總是成功。
我在stackoverflow上發現了一些舊帖子,似乎問題是相同的,但是我的結果與答案不匹配。我的環境是使用.Net Framework 4.51運行Visual Studio 2013的Windows 8.1。從網上,我想在我的類使用該解決方案之前,使工作的例子是在Microsoft.com
我轉換低於:
using System;
using System.Text;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Collections.Generic;
namespace XMLDemo
{
public class project
{
public static void Main()
{
string uri = @"C:\\events\items.xml";
string process_state = "Item";
string emails = StreamEmailAddress(uri, process_state);
}
private static string StreamEmailAddress(string uri, string process_state)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create(uri, settings);
string returnValue = "";
reader.MoveToContent();
while (reader.Read())
{
string x = reader.Value;
if ((string.IsNullOrEmpty(x) == false) && (x.Contains((char)13)))
{
returnValue = returnValue + x + "; ";
}
}
Console.WriteLine("Made it to the end: " + returnValue);
return returnValue;
}
}
}
你可以展示你的XML看起來如何? – Fabio
您的示例代碼中的邏輯看起來有缺陷。它應該是'&&!x.Contains'。 –
1)您應該跳過['XmlReader.NodeType'](https://msdn.microsoft.com/en-us/library/system.xml.xmlreader.nodetype.aspx)[[XmlNodeType.Whitespace]] (https://msdn.microsoft.com/en-us/library/system.xml.xmlnodetype.aspx)。檢查'XmlNodeType.Text','XmlNodeType.CDATA'和'XmlNodeType.SignificantWhitespace'。 2)除非您的XML文件很大,否則請勿使用此方法,而應使用[LINQ to XML](https://msdn.microsoft.com/en-us/library/bb387098.aspx)。 – dbc