2017-10-12 2 views
0

私は約67K行の巨大なXMLを持っています。 パラメータの正確な値がわかりません。 私は<Section>に必要なものが含まれており、その固有の名前は<Parameter>であることがわかります。XMLで一意の要素を見つけてC#の値を変更するにはどうすればよいですか?

XMLが同様になります。

<Configurations> 

<Configuration type="A"> 
<Configuration type="B"> 
<Configuration type="C"> 
<Section name="A">...</Section> 
<Section name="B">...</Section> 
<Section name="C"> 
<Parameter name="a" value="1" /> 
<Parameter name="specialStuff" value="this" /> 
</Section> 
<Section name="D">...</Section> 
... 
</Configuration> 
</Configuration> 
</Configuration> 
... 

</Configurations> 
</Document> 

どのように私はspecialStuffパラメータに到達し、その値を変更することができますか?

+0

を使用することができます。 https://msdn.microsoft.com/en-us/library/system.xml.xmlreader.read(v=vs.110).aspx – apomene

+0

を参照してください。このサンプルケースを超えて実際に複数の値を変更する必要がある場合は、代わりにXSL変換を使用します。 – Filburt

+0

少なくともあなたはそれを定量化しました。通常、人々が巨大なXMLを持っていると言うとき、私は100Mbか100Gbかを尋ねなければなりません。 –

答えて

1

あなたはXDocumentSetAttributeValue()を使用していることを行うことができます。

string xml = @" 
      <Configurations> 
       <Configuration type=""A""> 
        <Configuration type=""B"" > 
         <Configuration type=""C"" > 
          <Section name=""A"" ></Section> 
          <Section name=""Bv"" ></Section> 
          <Section name= ""C""> 
           <Parameter name= ""a"" value = ""1"" /> 
           <Parameter name= ""specialStuff"" value = ""this"" /> 
          </Section> 
          <Section name= ""D"" ></Section> 
         </Configuration> 
        </Configuration> 
       </Configuration> 
      </Configurations>"; 

XDocument xdoc = XDocument.Parse(xml); 
xdoc.Descendants("Parameter") 
    .Where(p => p.Attribute("name").Value == "specialStuff") 
    .FirstOrDefault()? 
    .SetAttributeValue("value", "youNewValue"); 

これは名前「パラメータ」とname属性specialStuffと最初に一致したタグのvalueを変更します。

メソッドDescendants() xmlにフィルタリングされた要素コレクション(ドキュメントオーダーあり)を指定のタグ名で返します( )。

あなたはname属性でより多くのParameterタグを持っている場合specialStuffに等しく、あなたはあなたのコレクションを取得し、それらを個別に変更することができます。

var specialStuffs = doc.Descendants("Parameter").Where(p => p.Attribute("name").Value == "specialStuff"); 
foreach (var item in specialStuffs) 
{ 
    item.SetAttributeValue("value", "newValue"); 
} 
+0

ありがとう、それは完璧です! – roll

+0

大歓迎です! – SeM

1

あなたは、XMLリーダーを使用するXPath

XmlDocument doc = new XmlDocument(); 
doc.Load(@"D:\Yourxml.xml"); 

XmlElement root = doc.DocumentElement; 
string qry = "//Parameter[@name='specialStuff']"; 
XmlNode node = root.SelectSingleNode(qry); 
node.Attributes["value"].Value = "newValue"; 

doc.Save(@"D:\Yourxml.xml"); 
+0

answareありがとうございます。 :) – roll

関連する問題