我正在尝试将单个行/节点(如下提供)添加到XML中:
<Import Project=".www\temp.proj" Condition="Exists('.www\temp.proj')" />
该行可能在XML的主/根节点下:
<Project Sdk="Microsoft.NET.Sdk">
我使用的方法:
XmlDocument Proj = new XmlDocument();
Proj.LoadXml(file);
XmlElement root = Proj.DocumentElement;
// Not sure about the next steps
root.SetAttribute("not sure", "not sure", "not sure");
尽管我不完全知道如何在XML中添加该行,因为这是我第一次尝试直接编辑XML文件,但该错误导致了另一个麻烦。
我第一次尝试时遇到此错误:
C#“ loadxml”'根级别的数据无效。第1行,位置1。'
知道此错误是一个著名的错误,其中一些在此链接中提供了多种方法:
xml.LoadData - Data at the root level is invalid. Line 1, position 1
不幸的是,大多数解决方案已经过时,在这种情况下答案不起作用,而且我不知道如何在这种情况下应用其他解决方案。
该问题的链接上提供/接受的答案:
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}
基本上它不起作用,原因是xml.StartsWith
似乎不再存在,同时xml.Remove
也不存在。
能否请您提供一段绕过错误并将代码添加到XML的代码?
编辑: 注释部分提供了示例XML文件。
答案 0 :(得分:2)
对于评论中发布的Xml,我使用了两种方法:
1-XmlDocument
XmlDocument Proj = new XmlDocument();
Proj.Load(file);
XmlElement root = Proj.DocumentElement;
//Create node
XmlNode node = Proj.CreateNode(XmlNodeType.Element, "Import", null);
//create attributes
XmlAttribute attrP = Proj.CreateAttribute("Project");
attrP.Value = ".www\\temp.proj";
XmlAttribute attrC = Proj.CreateAttribute("Condition");
attrC.Value = "Exists('.www\\temp.proj')";
node.Attributes.Append(attrP);
node.Attributes.Append(attrC);
//Get node PropertyGroup, the new node will be inserted before it
XmlNode pG = Proj.SelectSingleNode("/Project/PropertyGroup");
root.InsertBefore(node, pG);
Console.WriteLine(root.OuterXml);
2-使用XDocument
的Linq To XmlXDocument xDocument = XDocument.Load(file);
xDocument.Root.AddFirst(new XElement("Import",
new XAttribute[]
{
new XAttribute("Project", ".www\\temp.proj"),
new XAttribute("Condition", "Exists('.www\\temp.proj')")
}));
Console.WriteLine(xDocument);
要为XDocument
添加的命名空间:
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
两个解决方案都可以得到相同的结果,但是最后一个很简单。
希望您对此有帮助。
答案 1 :(得分:0)
您可以使用官方的MSBuild库吗?(https://www.nuget.org/packages/Microsoft.Build/)
我不确定仅读取和编辑项目文件实际上需要哪个nuget包。
我尝试直接以编程方式编辑MSBuild项目文件,因此不推荐这样做。由于意外更改,它经常损坏。 MSBuild库在编辑项目文件方面做得很好,例如添加属性,项目或导入。