我尝试过搜索答案,但没有找到解析这一段文本的正确方法:
<Hotspot X="-8892.787" Y="-121.9584" Z="82.04719" />
<Hotspot X="-8770.094" Y="-109.5561" Z="84.59527" />
<Hotspot X="-8755.385" Y="-175.0732" Z="85.12362" />
<Hotspot X="-8701.564" Y="-114.794" Z="89.48868" />
<Hotspot X="-8667.162" Y="-122.9766" Z="91.87251" />
<Hotspot X="-8802.135" Y="-111.0008" Z="82.53865" />
我想将每一行输出到:
Ex. X="-8892.787" Y="-121.9584" etc...
答案 0 :(得分:9)
如果您可以将其视为XML,那么这将是更好的方式,因此,请考虑将其视为:
<Hotspots>
<Hotspot X="-8892.787" Y="-121.9584" Z="82.04719" />
<Hotspot X="-8770.094" Y="-109.5561" Z="84.59527" />
<Hotspot X="-8755.385" Y="-175.0732" Z="85.12362" />
<Hotspot X="-8701.564" Y="-114.794" Z="89.48868" />
<Hotspot X="-8667.162" Y="-122.9766" Z="91.87251" />
<Hotspot X="-8802.135" Y="-111.0008" Z="82.53865" />
</Hotspots>
将其加载到XmlDocument
中,然后按如下方式解析:
var xml = "<Hotspots><Hotspot X=\"-8892.787\" Y=\"-121.9584\" Z=\"82.04719\" /></Hotspots>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode item in doc.SelectNodes("/Hotspots/Hotspot"))
{
Console.Write(item.Attributes["X"].Value);
Console.Write(item.Attributes["Y"].Value);
Console.Write(item.Attributes["Z"].Value);
// And to get the ouput you're after:
Console.Write("X=\"{0}\" Y=\"{1}\" Z=\"{2}\"",
item.Attributes["X"].Value,
item.Attributes["Y"].Value,
item.Attributes["Z"].Value);
}
注意:我在var xml = "..."
中使用了一个简化示例,使其更具可读性
答案 1 :(得分:4)
我猜你对你的开发技巧不太了解,但这不仅仅是文本,它是xml,你可以使用Linq To XML以这样的方式轻松访问它:
XDocument myXDoc = XDocument.Parse(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><root>{0}<root>", yourXmlString));
foreach (XElement hotspot in myXDoc.Root.Elements())
{
Console.WriteLine(string.Format("X=\"{0}\" Y=\"{1}\"", hotspot.Attribute("X").Value, hotspot.Attribute("Y").Value));
}
我会在XML和Linq To XML上阅读:
答案 2 :(得分:0)
假设每一行都以<Hotspot
...
//Lines are read into (for this example) a string[] called lines
List<string> valueLines = new List<string>();
foreach(string l in lines)
{
string x;
string y;
string z;
int xStart = l.IndexOf("X");
int yStart = l.IndexOf("Y");
int zStart = l.IndexOf("Z");
int closeTag = l.IndexOf(@"/");
StringBuilder vlBuilder = new StringBuilder();
vlBuilder.Append(l.Substring(xStart, (yStart - xStart - 1));
vlBuilder.Append(l.Substring(yStart, (zStart - yStart - 1));
vlBuilder.Append(l.Substring(zStart, (closeTag - zStart - 1));
valueLines.Add(vlBuilder.ToString());
}