如何解决VB.NET无法将字符串写入根节点
Dim doc As New XmlDocument()
Dim nodes As XmlNodeList
doc.Load("test.xml")
nodes = doc.SelectNodes("/Subjects/" & comboSubject.Text)
Dim fileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"test.xml")
Dim Rows As List(Of DataGridViewRow) =
gridTests.Rows.Cast(Of DataGridViewRow).Where(Function(row) Not row.IsNewRow).ToList
Dim xmlData As String =
<<%= comboSubject.Text %>>
<%= From row In Rows
Select
<attempt>
<test><%= CStr(row.Cells("Test").Value) %></test>
<score><%= CStr(row.Cells("Score").Value) %></score>
</attempt> %>
</>.ToString
For Each node As XmlNode In nodes
If node IsNot Nothing Then
node.ParentNode.RemoveChild(node)
doc.Save("test.xml")
End If
Next
如何将xmlData字符串写入“主题”节点?
<?xml version="1.0" encoding="UTF-8"?>
<Subjects>
<History>
<attempt>
<test>1999</test>
<score>75</score>
</attempt>
<attempt>
<test>1987</test>
<score>50</score>
</attempt>
<attempt>
<test>1789</test>
<score>25</score>
</attempt>
</History>
</Subjects>
每当我尝试将XmlData字符串写入test.xml时,它要么删除所有内容,要么什么都不做。我不确定我在做什么错。任何解决方案将不胜感激。
解决方法
我看到一些问题...
<Tooltip title={tooltipTitle} placement="right">
</Tooltip>
由于标记未正确关闭,因此这似乎无法产生有效的XML。例如,应该是Dim xmlData As String =
<<%= comboSubject.Text %>>
<%= From row In Rows
Select
<attempt>
<test><%= CStr(row.Cells("Test").Value) %></test>
<score><%= CStr(row.Cells("Score").Value) %></score>
</attempt> %>
</>.ToString
而不是</History>
此外,除了将其存储在xmlData变量中之外,您对该XML并没有做任何其他事情。该变量从不使用。您仅继续删除现有节点,这就是为什么您看到它“删除所有内容”的原因
</>
For Each node As XmlNode In nodes
If node IsNot Nothing Then
node.ParentNode.RemoveChild(node)
doc.Save("test.xml")
End If
Next
代表您的整个文档,而doc
将是node
,因此当您说/Subjects/History
时,您将从其节点中删除node.ParentNode.RemoveChild(node)
节点父History
节点,只剩下Subjects
被保存。此循环还将为每次迭代都调用save,但这不是必需的,但这既不是这里也不是那里。
最后,如上所述,您不会将<Subjects/>
写回到文档的任何位置。如何做到这一点并没有一个很好的答案,因为XML并非以这种方式构建为字符串。您可以使用XmlNode.InnerXml属性直接更改元素的标记,但是,正如Microsoft在文档中指出的那样,这不是一个好主意。您也可以将该字符串解析为XML对象,但理想情况下,您应该为要创建的每个元素构造Node对象,然后将它们添加到xmlData
的适当位置。像这样的例子:
doc
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。