Tôi có tệp xml như được đưa ra bên dưới.Thêm các nút con bằng cách sử dụng lớp C# Xdocument
<?xml version="1.0" encoding="utf-8"?>
<file:Situattion xmlns:file="test">
<file:Properties>
</file:Situattion>
Tôi muốn thêm các tập tin phần tử con: nhân vật sử dụng xDocument.So rằng xml cuối cùng của tôi sẽ như thế nào đưa ra dưới đây
<?xml version="1.0" encoding="utf-8"?>
<file:Situattion xmlns:file="test">
<file:Characters>
<file:Character file:ID="File0">
<file:Value>value0</file:Value>
<file:Description>
Description0
</file:Description>
</file:Character>
<file:Character file:ID="File1">
<file:Value>value1</file:Value>
<file:Description>
Description1
</file:Description>
</file:Character>
</file:Characters>
Mã trong C# tôi đã cố gắng sử dụng lớp XDocument được đưa ra dưới đây.
XNamespace ns = "test";
Document = XDocument.Load(Folderpath + "\\File.test");
if (Document.Descendants(ns + "Characters") != null)
{
Document.Add(new XElement(ns + "Character"));
}
Document.Save(Folderpath + "\\File.test");
Tại dòng "Document.Add(new XElement(ns + "Character"));
", tôi nhận được một lỗi:
"This operation would create an incorrectly structured document."
.
Làm cách nào để thêm nút trong "file:Characters
".
bạn đã xem xét sử dụng 'XPATH' hoặc' XQuery' cũng nhìn vào liên kết '-> Related' nằm ở bên phải của trang hiện tại này, rất nhiều ví dụ làm việc để bạn điều tra – MethodMan
@DJKRAZE: Không cần để sử dụng XPath hoặc XQuery ở đây, và tôi không tin họ thậm chí còn làm cho mã đơn giản hơn. –