【问题标题】:Reading Script File Specifically C#专门读取脚本文件 C#
【发布时间】:2014-08-06 08:36:47
【问题描述】:

所以我有一个元文件,其中包含部分如下所示的长脚本。 我只在这里发帖是因为我注意到你们回复的速度有多快,而且这已经困扰了我好几个小时(字面意思)-我是新人

示例脚本

<?xml version="1.0" encoding="UTF-8"?>

<CHandlingDataMgr>
  <HandlingData>
    <Item type="CHandlingData">
      <handlingName>Car1</handlingName>
      <fMass value="140000.000000" />
      <fInitialDragCoeff value="30.000000" />
      <fPercentSubmerged value="85.000000" />
      <vecCentreOfMassOffset x="0.000000" y="0.000000" z="0.000000" />
      <vecInertiaMultiplier x="1.000000" y="1.000000" z="1.000000" />

    </Item>
  </HandlingData>
</CHandlingDataMgr>

我想要获得的输出是:

Car1, 140000.000000, 30.000000, 85.000000, "0.000000" "0.000000" "0.000000",  etc 

(所有没有脚本元素的值和名称)`

注意:上述脚本针对不同的汽车多次出现,所有值也不同。

如果使用相同的结构,我还希望我的朋友能够在与我的文件链接的同一目录中将我的“Cars.Meta”文件替换为他们自己的文件。

在我的程序的更高版本中,我希望在列表框中列出这些汽车及其所有找到的数据。 我没有在网上找到任何关于内联字/数字抓取的信息,我相信是因为搜索的具体程度? 提前感谢您提供的任何帮助:-)

【问题讨论】:

  • 你的文件会是格式良好的xml吗?
  • 是的,该文件包含超过 40 个名称,每个名称大约有 10 个选项
  • 你能多发一点文件吗?完整的结构是什么?比如:&lt;people&gt;&lt;person&gt;&lt;name&gt;Bob&lt;/name&gt;&lt;/person&gt;&lt;person&gt;&lt;name&gt;John&lt;/name&gt;&lt;/person&gt;&lt;/people&gt;
  • 编辑主帖以包含实际文件,谢谢

标签: c# find word


【解决方案1】:

您需要做的是将文件解析或加载到支持查询所需内容的合适对象中。 System.Xml.Linq.XDocument 就是这样一个例子。

这里有一些代码让你开始:

// xml is your Xml file as a string
var doc = XDocument.Parse(xml);

// You could also load it from a file if you wanted
// var doc = XDocument.Load(fileLocation);


// You can now query the XDocument with Linq

// E.g. using fluent syntax
var items = doc.Descendants("HandlingData").Elements("Item");

// Or use the query expression syntax
var query = from i in items 
            select new { 
                HandlingName = (string)i.Element("handlingName"), 
                Mass = (decimal?)i.Element("fMass").Attribute("value") 
            };

Console.WriteLine("{0} - {1}", query.First().HandlingName, query.First().Mass);
// Prints: Car1 - 140000.000000

查看 MSDN 文档,关于 XDocument 的 SO 上有无数问题。

祝你好运:)

【讨论】:

  • 感谢您的回复,但是找不到 XDocument 并且 XMLDocument 不包含 .Parse 方法
  • 确保您有System.Xml.Linq.dll 的引用,并且您的文件顶部有一个using System.Xml.Linq;。您使用的是哪个版本的 .Net?
猜你喜欢
  • 1970-01-01
  • 2013-02-07
  • 2014-10-26
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2021-03-10
  • 2015-05-16
相关资源
最近更新 更多