我在研究如何将元素添加到我的 XML 文档中时遇到了一些麻烦, 我想将热点信息添加到 Id 正确的 xml 中(因此在 id=2 中添加热点信息)这是我当前的 XML -
<Pages>
<Page>
<Id>1</Id>
<Title>TEST</Title>
<ContentUrl>Images\testimg.png</ContentUrl>
<Hotspots>
<Hotspot>
<X>140</X>
<Y>202</Y>
<Shape>Circle</Shape>
<TargetId>2</TargetId>
</Hotspot>
</Hotspots>
<ParentId>0</ParentId>
</Page>
<Page>
<Id>2</Id>
<Title>TEST2</Title>
<ContentUrl>Images\testimg2.jpg</ContentUrl>
<Hotspots>
</Hotspots>
<ParentId>1</ParentId>
</Page>
</Pages>
我想要更新 xml,以便它显示类似这样的内容 -
<Pages>
<Page>
<Id>1</Id>
<Title>TEST</Title>
<ContentUrl>Images\testimg.png</ContentUrl>
<Hotspots>
<Hotspot>
<X>140</X>
<Y>202</Y>
<Shape>Circle</Shape>
<TargetId>2</TargetId>
</Hotspot>
</Hotspots>
<ParentId>0</ParentId>
</Page>
<Page>
<Id>2</Id>
<Title>TEST2</Title>
<ContentUrl>Images\testimg2.jpg</ContentUrl>
<Hotspots>
<Hotspot>
<X>140</X>
<Y>202</Y>
<Shape>Circle</Shape>
<TargetId>2</TargetId>
</Hotspot>
</Hotspots>
<ParentId>1</ParentId>
</Page>
我现在的代码是-
XDocument Xdoc = XDocument.Load(@"Test.xml");
Xdoc.Root.Element("Pages").Elements("Page").Where(Page => Page.Value.Substring(0,Page.Value.IndexOf("-"))==CurrentPage.Id.ToString())
.FirstOrDefault()
.Add(new XElement("Hotspot",
new XElement("X", x),
new XElement("Y", y),
new XElement("Shape", "Circle"),
new XElement("TargetId", nNodeID)
));
Xdoc.Save(@"Test.xml");
(CurrentPage.Id 是我想要与用于添加热点的 XML 文档匹配的 ID - Page.Value.IndexOf("-") 返回 xml 中页面的 ID)
但这只是在页面底部添加了代码,所以我需要找到一种方法将其添加到正确 ID 所在的 XML 的热点部分。
任何帮助将不胜感激,如果有更好的方法来做我正在尝试的事情,请告诉我,我以前从未在我的代码中实际使用过 XML 文档,并且最近才开始学习 c#(在上个月内) ).
谢谢。
最佳答案
选择你需要的页面
XDocument xdoc = XDocument.Load("Test.xml");
int pageId = 2;
var page = xdoc.Descendants("Page")
.FirstOrDefault(p => (int)p.Element("Id") == pageId);
然后向这个页面元素添加内容(如果有的话):
if (page != null)
{
// add to Hotspots element
page.Element("Hotspots")
.Add(new XElement("Hotspot",
new XElement("X", x),
new XElement("Y", y),
new XElement("Shape", "Circle"),
new XElement("TargetId", nNodeID)));
xdoc.Save("Test.xml");
}
您的代码将新的热点元素添加到页面,而不是将内容添加到现有的热点元素。
关于c# - 使用 C# 编辑 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407001/