我想将xml文件读出到文本块中,并且用户可以在文本块中编辑此文本,并将附加更改应用回xml文件中。到目前为止,这是我所做的:

    private void Editbuildstreams_Click(object sender, RoutedEventArgs e)
    {
        BuildstreamTextblock.Visibility = Visibility.Visible;
        using (StreamReader srr = new StreamReader("initial.xml"))
        {
            string line;
            while ((line = srr.ReadLine()) != null)
            {
                BuildstreamTextblock.Text = line;
            }
        }
    }


这是xml文件的结构:

<xml>
   <email>
..
   </email>
   <buildstream1>
      <path value="apple"/>
   </buildstream1>
   <buildstream2>
      <path value="pear"/>
      <path value="bananas"/>
   </buildstream2>
</xml>


问题是:

我如何读出xml文件的行?

我只对获取xml文件的某些部分感兴趣。如何仅读取<buildstream1><buildstream2>

最佳答案

像这样吗

var originalDocument = XDocument.Load(fileName);
var originalElement = originalDocument.XPathSelectElement("xml/buildstream1");
textBox.Text = originalElement.ToString();

// do changes in the text box

var newDocument = XDocument.Parse(textBox.Text);
var newElement = newDocument.Elements().Single();

// insert edited element
originalElement.AddAfterSelf(newElement);

// remove original element
originalElement.Remove();
originalDocument.Save(fileName);

// or

var resultXml = originalDocument.ToString();

关于c# - streamreader读取xml文件的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6339921/

10-11 15:20
查看更多