1

这是 XML 示例:

  <?xml version="1.0" ?> 
  <XMLScreen xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <CX>80</CX> 
  <CY>24</CY> 
  <Formatted>true</Formatted> 
  <Field>
  <Location position="1" left="1" top="0" length="69" /> 
  <Attributes Base="226" Protected="false" FieldType="High" /> 
  *SDC SCHEDULING CATEGORY UPDATE 
  </Field>
  </XMLScreen>

我想根据其检索每个字段的内部文本Location position

到目前为止,我所拥有的是:

  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.LoadXml(myEm.CurrentScreenXML.GetXMLText());
  XmlNodeList fields = xmlDoc.GetElementsByTagName("Field");

  MessageBox.Show("Field spot: " + i + " Contains: " + fields[i].InnerText);

而且我希望能够通过传入一些位置位置来提取字段的内部文本。所以如果我说foo[i]我希望能够得到内文

*SDC 计划类别更新

4

3 回答 3

0

Something like that, with XDocument instead of XmlDocument (well, if you're not in .net 3.5 or higher, we'll have a problem).

private string GetTextByLocationId(XDocument document, int id)
{
     var field = document.Descendants("Field").FirstOrDefault(m => m.Element("Location").Attribute("position").Value == id.ToString());
     if (field == null) return null;
     return field.Value;
}

and usage

var xDocument = XDocument.Load(<pathToXmlFile or XmlReader or string or ...>);
var result = GetTextByLocationId(xDocument, 1);

EDIT

or if you want a dictionary with :key = position / value = text

private static Dictionary<int, string> ParseLocationAndText(XDocument document)
        {
            var fields = document.Descendants("Field");
            return fields.ToDictionary(
                 f => Convert.ToInt32(f.Element("Location").Attribute("position").Value),
                 f => f.Value);
        }
于 2012-07-20T16:24:39.073 回答
0

尝试,

XElement root = XElement.Parse(myEm.CurrentScreenXML.GetXMLText());
XElement field = root.XPathSelectElement(
                    string.Format("Field[Location/@position='{0}']", 1));
string text = field.Value;

您将需要使用以下内容才能将 XPath 与 XElements 一起使用。

using System.Xml.XPath;
于 2012-07-20T19:18:11.287 回答
0

您应该使用 xpath 搜索查询:

  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.LoadXml(xml);
  int nodeId = 4;
  XmlNode node = xmlDoc.SelectSingleNode(String.Format(@"//Location[@position='{0}']", nodeId));
  if (node != null)
  {
      String field = node.ParentNode.InnerText;
  }
于 2012-07-20T16:35:54.087 回答