我有一个非常大的XML文件,所以我在C#中使用XmlReader。问题是某些内容包含不应由XmlReader处理的类似XML的标记。
<Narf name="DOH">Mark's test of <newline> like stuff</Narf>
这是遗留数据,因此无法重构......(当然)
我已经尝试了ReadInnerXml但获得了整个节点。我已经尝试过ReadElementContentAsString,但得到一个例外,说'newline'没有关闭。
// Does not deal with markup in the content (Both lines)
ms.mText = reader.ReadElementContentAsString();
XElement el = XNode.ReadFrom(reader) as XElement; ms.mText = el.ToString();
我想要的是ms.mText等于“Mark的测试<newline>喜欢的东西”而不是例外。
System.Xml.XmlException was unhandled
HResult=-2146232000
LineNumber=56
LinePosition=63
Message=The 'newline' start tag on line 56 position 42 does not match the end tag of 'Narf'. Line 56, position 63.
Source=System.Xml
重复标记的问题无法解决问题,因为它需要更改输入以在使用数据之前删除问题。如上所述,这是遗留数据。
我根据这里的回答想出来了!不优雅,但有效......
public class TextWedge : TextReader
{
private StreamReader mSr = null;
private string mBuffer = "";
public TextWedge(string filename)
{
mSr = File.OpenText(filename);
// buffer 50
for (int i =0; i<50; i++)
{
mBuffer += (char) (mSr.Read());
}
}
public override int Peek()
{
return mSr.Peek() + mBuffer.Length;
}
public override int Read()
{
int iRet = -1;
if (mBuffer.Length > 0)
{
iRet = mBuffer[0];
int ic = mSr.Read();
char c = (char)ic;
mBuffer = mBuffer.Remove(0, 1);
if (ic != -1)
{
mBuffer += c;
// Run through the battery of non-xml tags
mBuffer = mBuffer.Replace("<newline>", "[br]");
}
}
return iRet;
}
}