c# - 卡在编辑 XML 文件

标签 c# xml nodes

第一次发帖在这里..:D 所以,我一直在编辑我的 XML 文件并添加新节点。 这是我的 XML 的样子:

    <?xml version="1.0" encoding="utf-8"?>
    <Racuni>
    <------ I want to make new <racun> here with new data imported from list or at the end 
      <Racun>
        <datumkreiranjaracuna>20191230</datumkreiranjaracuna>
        <nazivulja>suncokretovo</nazivulja>
        <kolicinaulja>50</kolicinaulja>
        <cijenaulja>25</cijenaulja>
      </Racun>
    <------- or here :D
    </Racuni>

我想添加新的RacunRacuni 之间每次我打开我的控制台应用程序时都会使用列表中的新数据。 (不管它是在第一个 Racun 之前还是在最后一个 Racun 之后)我只想把它保存在那里。

提前致谢!

编辑:

有没有办法改变特定的<cijenaulja> ? 我将整个 xml 文档加载到一个列表中,然后我想更改 <cijenaulja>thisvalue</cijenaulja> 中的特定值 然后如何保存新值?

最佳答案

也许你应该使用 XmlDocument 因为它更容易处理你描述的这样的任务:

var xdoc = new XmlDocument();
    xdoc.LoadXml(@"
    <?xml version='1.0' encoding='utf-8'?>
    <Racuni>
    <!-- I want to make new <racun> here with new data imported from list or at the end -->
      <Racun>
        <datumkreiranjaracuna>20191230</datumkreiranjaracuna>
        <nazivulja>suncokretovo</nazivulja>
        <kolicinaulja>50</kolicinaulja>
        <cijenaulja>25</cijenaulja>
      </Racun>
    <!-- or here :D -->
    </Racuni>");

// you must use the original XmlDocument to create new elements
var racun = xdoc.CreateElement("Racun");
var dat = xdoc.CreateElement("datumkreiranjaracuna");
    dat.InnerText = "20191230";
var naz = xdoc.CreateElement("nazivulja");
    naz.InnerText = "suncokretovo";
var kol = xdoc.CreateElement("kolicinaulja");
    naz.InnerText = "50";
var cij = xdoc.CreateElement("cijenaulja");
    naz.InnerText = "25";

// now, add the created nodes into the proper places
racun.AppendChild(dat);
racun.AppendChild(naz);
racun.AppendChild(kol);
racun.AppendChild(cij);

// finally, add the new element back into the xml document
//xdoc.DocumentElement.AppendChild(racun);
xdoc.SelectSingleNode("/Racuni").AppendChild(racun);

// display the results
xdoc.Save(Console.Out);

您还应该查看 CreateAttribute 等方法,并了解如何使用 XPath 定位特定元素。

关于c# - 卡在编辑 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225682/

相关文章:

php - 我的应用程序正在向服务器发送 XML 文件 : need some guidance on writing a PHP script to parse the XML file

javascript - 将对象序列化为 XML 会破坏结构定义

apache-spark - 如何获取 Spark MLlib 随机森林中每个树节点的记录数/类分布?

python - 使用Python遍历Neo4j数据库

c# - 无法对 System.Int32 和 System.String 执行 'Like' 操作。 DataGridView 搜索和过滤

c# - 将 json 字符串反序列化为对象 - Silverlight

c# - 为什么 var 被解析为 Double 而不是 Long?

c# - 带有 List<> 项目的玻璃映射器 Editable() 不工作?

java - 使用 Eclipse 的 xml 智能感知?

java - 只绘制应该在屏幕上的节点?