我找到了两个解决方案。两者都不是很好,但也许你可以告诉我哪个缺点更少。
这两种解决方案都直接依赖于使用“XmlTextReader”而不是“XmlReader”。它带有属性“LinePosition”,它引导我找到第一个解决方案,并使用方法“ReadChars”作为第二个解决方案的基础。
解决方案(1),通过索引从原始字符串中获取数据
问题:
代码
string TXML = @"<xml><data></data><rawnode at=""10 4""><text>hallöle</text><z d=""2"">3</z></rawnode><data></data></xml>";
//XmlReader r = XmlReader.Create(new StringReader(TXML));
XmlTextReader r = new XmlTextReader(new StringReader(TXML));
// read to node which shall be retrived "raw"
while ( r.Read() )
{
if ( r.Name.Equals("rawnode") )
break;
}
// here we start
int Begin = r.LinePosition;
r.Skip();
int End = r.LinePosition;
// get it out
string output=TXML.Substring(Begin - 2, End - Begin);
解决方案 (2),使用“ReadChars”获取数据
问题:
- 我必须解析并重新创建我想阅读的标签的“外部”标记。
- 这可能会降低性能。
- 我可能会引入错误。
代码:
// ... again create XmlTextReader and read to rawnode, then:
// here we start
int buflen = 15;
char[] buf = new char[buflen];
StringBuilder sb= new StringBuilder("<",20);
//get start tag and attributes
string tagname=r.Name;
sb.Append(tagname);
bool hasAttributes = r.MoveToFirstAttribute();
while (hasAttributes)
{
sb.Append(" " + r.Name + @"=""" + r.Value + @"""");
hasAttributes = r.MoveToNextAttribute();
}
sb.Append(@">");
r.MoveToContent();
//get raw inner data
int cnt;
while ((cnt = r.ReadChars(buf, 0, buflen)) > 0)
{
if ( cnt<buflen )
buf[cnt]=(char)0;
sb.Append(buf);
}
//append end tag
sb.Append("</" + tagname + ">");
// get it out
string output = sb.ToString();