我在解决如何将元素添加到 XML 文档中时遇到了一些麻烦,
我想将热点信息添加到 xml 中,其中 Id 正确(因此 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)
但这只是在页面底部添加代码,因此我需要找到一种方法将其添加到 XML 的热点部分,其中正确的 Id 所在。
任何帮助将不胜感激,如果有更好的方法来做我正在尝试的事情,请告诉我,我以前从未在代码中实际使用过 XML 文档,并且最近才开始学习 C#(上个月内)。
thanks.