我試圖從WPF創建一個工具,該工具通過將數據輸入到文本框中創建一個簡單的XML文檔,然後單擊一個按鈕將該數據輸入到XML文檔中。除了根元素,我將有一個孩子分步驟元素的腳步元素像這樣:C#,試圖將子節點添加到具有特定屬性的節點
<root>
<step id="1">
<P>some instructions</p>
<step id="1.1">
<p>some additional instructions</p>
</step>
</step>
<step id="2">
<p>second set of instructions</p>
<step id="2.1">
<p>additional instructions for step 2</p>
</step>
</step>
我已經能夠添加父步驟,但是我所有的子步驟,屬於第一父下步驟:
<root>
<step id="1">
<step id="1.1">
<step id="2.1">
<step id="3.1">
<step id="2">
<step id="3">
我想使用XPath插入我的子步驟到適當的父步驟。但是,我收到錯誤: 「XAttribute不包含'add'的定義,並且沒有找到接受第一個參數類型'XAttribute'的擴展方法'add'」。
我已經廣泛搜索,無法提出解決方案,希望這是有道理的,有人可以幫我一把。先謝謝你。這裏是我的代碼:
using System.Windows;
using System.Xml.Linq;
using System.Xml.XPath;
namespace XMLwpfTest1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
XDocument doc = new XDocument(
new XElement("Content",
new XElement("Title", "DM Title"))
);
string par = "par-";
int counter = 1;
int counter2 = 1;
string stepNumber = "";
public MainWindow()
{
InitializeComponent();
}
private void create_Click(object sender, RoutedEventArgs e)
{
doc.Element("Content").Add(
new XElement("proceduralStep",
new XAttribute("id", par + counter.ToString("D4")),
new XElement("para",
dataBox.Text)));
stepNumber = par + counter.ToString("D4");
counter += 1;
dataBox.Clear();
counter2 = 1;
}
private void createSubStep_Click(object sender, RoutedEventArgs e)
{
var addStep = doc.XPathSelectElement("Content/proceduralStep").Attribute(stepNumber);
addStep.add(
new XElement("proceduralStep",
new XAttribute("id", stepNumber + "-" + counter2.ToString("D4")),
new XElement("para",
subDataBox.Text)));
counter2 += 1;
subDataBox.Clear();
}
private void save_Click(object sender, RoutedEventArgs e)
{
doc.Save(fileName.Text + ".xml");
savedLabel.Visibility = Visibility.Visible;
}
}
}
這是一個完整的xml文件嗎?內容/程序步驟和內容來自哪裏?我沒有在xml中看到它們。 – Sybren
我在問題中提出的XML只是我正在尋找的結構。這些不是實際的標籤名稱。我應該把我使用的實際標籤名稱。對困惑感到抱歉。和是將要創建的元素。 –
swm462