2016-09-15 4 views
0

아래 XML 파일이 있습니다. 장르, 제목, 작성자, ISBN과 같은이 XML 파일의 Detail 값만 수정하려고합니다. 마지막으로 파일은 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 
    } 
}