bmw318mt Ответов: 1

Итерация по XML-документу


У меня есть XML-документ, и я хочу перебирать его до тех пор, пока не найду конкретный элемент и не получу значение в определенном атрибуте.

XML представляет собой следующий фрагмент кода

<?xml version="1.0" encoding="utf-8"?>
<Eib:Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="" modificationDate="2015-08-14T17:15:11.647" version="1702.02.00BUILD202_DISCO" remoteShutdownAllowed="true" ModelBuilderVersion="6.3" E39Compatible="false" xmlns:Eib="urn:peergroup-com:Eib">
  <Eib:Log name="LogManager">
    <Eib:DatedFileLog rolloverOnStartup="true" rolloverOnMidnight="true" rolloverOnSize="5000" rolloverAgeLimit="0" rolloverFileCountLimit="0" logFilePath="C:\Temp\Logs" loggingLevel="4" enabled="true" />
  </Eib:Log>
  <Eib:Units enabled="true">
    <Eib:Unit name=" per min" symbol="/min" enabled="true" />
    <Eib:Unit name="10x6deg" symbol="10^-6deg" enabled="true" />
    <Eib:Unit name="10x_3deg" symbol="10^-3deg" enabled="true" />
    <Eib:Unit name="bps" symbol="bps" enabled="true" />
    <Eib:Unit name="chips" symbol="chips" enabled="true" />
    <Eib:Unit name="kilobel" symbol="kB" enabled="true" />
    <Eib:Unit name="lines" symbol="lines" enabled="true" />
    <Eib:Unit name="mJ per cm2" symbol="mJ/cm2" enabled="true" />
    <Eib:Unit name="nanometer per second (plane)" symbol="nm/sec" enabled="true" />
    <Eib:Unit name="Pixel" symbol="Pixel" enabled="true" />
    <Eib:Unit name="Times" symbol="Times" enabled="true" />
    <Eib:Unit name="works" symbol="works" enabled="true" />
  </Eib:Units>
  <Eib:Clock name="Clock" clockSetMethod="useOffset" />
  <Eib:ExceptionManager name="ExceptionManager" />
  <EibModel:EquipmentElements>
        <EibModel:Module name="GenericService" elementType="GenericService" function="GenericService" immutableID="GenericService" make="GenericService" model="GenericService" modelRevision="GenericService" supplier="GenericService" pollingInterval="0" processName="GenericService" processType="Process" recipeType="GenericService" enabled="true">
            <EibModel:CustomAttributes enabled="true">
              <EibModel:CustomAttribute name="ACCUM_UNIT_PROCESSED_RUNTIME_COUNTER" parameterType="Double" group="GenericService" value="0" classification="Configuration" accessLevel="0" persistValue="false" enabled="true" />
			  <EibModel:CustomAttribute name="TEMP_PATH" parameterType="StringData" group="GenericService" value="C:\Temp\DS-DISCO-DFD6361-017" classification="Configuration" accessLevel="0" persistValue="false" enabled="true" />
              <EibModel:CustomAttribute name="THRESHOLD" parameterType="IntegerCount" group="GenericService" value="5" classification="Configuration" accessLevel="0" persistValue="false" enabled="true" />
            </EibModel:CustomAttributes >
		  </EibModel:Module>    
		<EibModel:IODevice name="EquipmentConstantsContainer" uid="7eec9303-6f9f-4c10-ab78-8cd5435730ff" elementType="EquipmentConstantsContainer" function="EquipmentConstantsContainer" immutableID="EquipmentConstantsContainer" make="EquipmentConstantsContainer" model="EquipmentConstantsContainer" modelRevision="EquipmentConstantsContainer" supplier="EquipmentConstantsContainer" pollingInterval="0" enabled="true">
            <EibModel:CustomAttributes enabled="true">
              <EibModel:CustomAttribute name="AB_MODE" parameterType="StringData" group="EquipmentConstants" classification="Configuration" description="Min: NORMAL, Max: SPECIAL" accessLevel="0" persistValue="false" enabled="true" />
			</EibModel:CustomAttributes>
		</EibModel:IODevice>
	</EibModel:EquipmentElements>


Я хочу получить 1 конкретное значение в элементе допустим я хочу значение TEMP_PATH

Что я уже пробовал:

if (!isFound)
            {
                if (currentNode.Name != "EibModel:CustomAttribute")
                {
                    //check if node has children
                    if (currentNode.HasChildNodes)
                    {
                        XmlNodeList nodelist = currentNode.ChildNodes;

                        foreach (XmlNode node in nodelist)
                        {
                            checkNode(eibPath, node);
                        }
                    }
                    else //has no children
                    {
                        if (currentNode.NextSibling != null)
                        {
                            checkNode(eibPath, currentNode.NextSibling);
                        }
                    }
                }
                else if (currentNode.Name == "EibModel:CustomAttribute")
                {
                    if (currentNode.OuterXml.Contains("EQP_NAME"))
                    {
                        eqpName = currentNode.Attributes.GetNamedItem("value").Value;
                        tempPath = string.Concat(tempPath + eqpName);
                    }
                    if (currentNode.OuterXml.Contains("TEMP_PATH"))
                    {
                        isFound = true;
                        if (txtResults.Text != string.Empty)
                            txtResults.AppendText(Environment.NewLine);

                        txtResults.AppendText("Attempting to Process File : " + eibPath + Environment.NewLine);
                        string val = currentNode.Attributes.GetNamedItem("value").Value;

                        //create directory before changing EIB file
                        log.Info("Attempting to create folder: " + tempPath);
                        // Determine whether the directory exists.
                        if (Directory.Exists(tempPath))
                        {
                            txtResults.SelectionColor = Color.OrangeRed;
                            txtResults.AppendText(tempPath + " already exists." + Environment.NewLine);
                        }
                        else
                        {
                            // Try to create the directory.
                            DirectoryInfo di = Directory.CreateDirectory(tempPath);
                            txtResults.SelectionColor = Color.Green;
                            txtResults.AppendText(tempPath + " created succesfully." + Environment.NewLine);
                        }
                        currentNode.Attributes.GetNamedItem("value").Value = val.Replace(val, tempPath);
                        txtResults.AppendText("Old TEMP_PATH= " + val + " New TEMP_PATH= " + tempPath + Environment.NewLine);
                        //return isFound;                    
                    }
                }
                else { };                   
            }
            return isFound;
        }

Kornfeld Eliyahu Peter

XPath?

1 Ответов

Рейтинг:
0

#realJSOP

Я бы построил поддерживающую модель в коде, загрузил и проанализировал весь xml-файл, а затем использовал LINQ на модели, чтобы найти то, что мне нужно.