我对XML和c#相当陌生,所以如果这个问题太容易问,请理解。
我正在使用c# win-form应用程序转换XML格式。应用程序使用"OpenFileDialog"打开一个xml文件,然后转换将被执行(这已经完成,但我仍然需要添加或删除一些更像下面)。转换后,应用程序将使用'SaveFileDialog'保存修改后的xml文件。
原始XML格式
<?xml version="1.0" encoding="utf-8" ?>
<DataList>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
..<Data></Data> continued...
</DataList>
我想编辑XML文件如下
<?xml version="1.0" encoding="utf-8" ?> **→ Remove this delaration!**
<MainInterface> **→ Add 'root element' before existing nodes**
<DataList>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
..<Data></Data> continued...
</DataList>
</MainInterface> **→ close newly added root element**
我试过下面的代码,但似乎不工作
OpenFileDialog openFileDialogue = new OpenFileDialog();
openFileDialog1.DefaultExt = "xml";
openFileDialog1.Filter = "xml files (*.xml)|*.xml";
openFileDialog1.Title = "Select a xml File";
openFileDialog1.ShowDialog();
XDocument xmlFile = XDocument.Load(openFileDialog1.FileName);
**// Remove Declaration**
XDocument doc = new XDocument(new XDeclaration(null, null, null));
**// Add Root Element**
XElement doc1 = XElement.Parse(openFileDialog1.FileName);
XElement root = new XElement("MainInterface", doc1);
//doc.Save(_data)
openFileDialog1.FileName = root.ToString();
-----------------------------------------------------------------------------------
Do something for conversion ~~~
-----------------------------------------------------------------------------------
SaveFileDialog saveFileDialogue1 = new SaveFileDialog();
saveFileDialog1.Filter = "xml File |*.xml";
saveFileDialog1.Title = "Conversion Completed! Save a XML file";
saveFileDialog1.FileName = "XML Converted.xml";
saveFileDialog1.ShowDialog();
xmlFile.Save(saveFileDialog1.FileName);
我应该使用XML Writer吗?是否有更简单的方法来删除声明并在现有xml文件上添加根元素?
这是您的XML结构吗?还是一定会改变?
查看我的解析方法:
var xDoc = XDocument.Load(openFileDialog1.FileName);
//Use code below if you'll use string to Load XDocument
/*var xmlString = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<DataList>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data>
<ID>1</ID>
<Name>Mike</Name>
<Age>23</Age>
</Data>
<Data></Data> continued...
</DataList>
";
var xDoc = XDocument.Parse(xmlString);*/
var dataList = xDoc.Descendants(@"Data");
var newXDoc = new XDocument(new XDeclaration(null, null, null),
new XElement("MainInterface",
new XElement("DataList",
dataList.Select(data =>
new XElement("Data",
data.Element("ID"),
data.Element("Name"),
data.Element("Age")
)
)
)
)
);
只要得到xml as string
并玩它!要删除标题,您可以使用Replace
功能!添加根元素只是add <MainInterface> to the begining and </MainInterface> to the end
的xml字符串
要转换为字符串,可以使用XDocument.ToString()