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

そのようなもので、XmlDocumentの代わりにXDocumentを使用します(.net 3.5以降を使用していない場合は、問題が発生します)。

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;
}

と使用法

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

編集

または、: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

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 に答える
0

試す、

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

XElements で XPath を使用するには、次を使用する必要があります。

using System.Xml.XPath;
于 2012-07-20T19:18:11.287 に答える