2016-09-15 4 views
0

У меня есть следующий XML-файл. Я хочу изменить только значения Detail в этом XML-файле, такие как Genre, Title, Writer, ISBN. И, наконец, файл должен быть сохранен с измененными изменениями с помощью C#.изменить значения встроенных узлов в файле XML

<Book> 
<LibraryCode>LIB-0001</LibraryCode> 

<BookDetail> 
    <Detail Name="Genre" Value="fiction" /> 
    <Detail Name="Title" Value="Book of thrones" /> 
    <Detail Name="Writer" Value="King of Thrones" /> 
    <Detail Name="ISBN" Value="108y387527" /> 
</BookDetail> 
</Book> 

, пожалуйста, предложите мне оптимальное решение для этого.

ответ

0

Вы можете прочитать xml-файл в строке, используйте System.Xml для его обработки, а затем сохраните его снова. Что-то вроде этого:

StringBuilder sb = new StringBuilder(); 
    using (StreamReader sr = new StreamReader("YourFile.xml")) 
    { 
     String line; 
     // Read and display lines from the file until the end of 
     // the file is reached. 
     while ((line = sr.ReadLine()) != null) 
     { 
      sb.AppendLine(line); 
     } 
    } 
    string xmlString = sb.ToString(); 

    var doc = new XmlDocument(); 
    doc.Load(new StringReader(xmlString)); 

    XmlNodeList nodes = doc.GetElementsByTagName("Detail"); 
    foreach (XmlElement no in nodes) 
    { 
     XmlAttribute attr = doc.CreateAttribute("ISBN"); 
     attr.InnerText = "12345"; 
     no.Attributes.Append(attr); 
    } 

    using (StreamWriter writer = new StreamWriter("YourFile.xml", false)) 
    { 
     writer.WriteLine(doc.ToString()); 
    } 
0

Я нашел, что приведенный ниже код работает исправно и решил мою проблему.

XmlDocument doc = new XmlDocument(); 
doc.Load(FilePath); 
XmlNodeList aNodes = doc.SelectNodes("/Book/BookDetail/Detail"); 
foreach (XmlNode aNode in aNodes) 
{ 
    XmlAttribute NameAttribute = aNode.Attributes["Name"]; 
    XmlAttribute ValueAttribute = aNode.Attributes["Value"]; 

    if (NameAttribute != null) 
    { 
    string currentValue = NameAttribute.Value; 
    if (currentValue == "ISBN") 
    { 
     ValueAttribute.Value = ISBN_value; 
    } 
    //Likewise we can change values of all the inline nodes in XML 
    } 
} 
Смежные вопросы