c# - 如何使用 XDocument 更新具有命名空间要求的现有 xml 文件?
问题描述
我的 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns="http://a01_data_navin"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://a01_data_navin event.xsd">
<Event>
<eventid>1</eventid>
<Photo>
<filepath>files\images\memory rep02.png</filepath>
<location>
<lat>35.496456056584158</lat>
<lon>-99.228515625</lon>
</location>
<datetimestamp>2020-03-29T00:00:00</datetimestamp>
</Photo>
</Event>
<Event>
<eventid>2</eventid>
<Photo>
<filepath>files\images\poop.jpeg</filepath>
<location>
<lat>36.137874718407268</lat>
<lon>-89.6044921875</lon>
</location>
<datetimestamp>2020-03-29T00:00:00</datetimestamp>
</Photo>
</Event>
</Root>
当我在 C# 中使用 XDocument
XDocument xml = XDocument.Load(_xmlFilePath);
// create xml structure
var photo_XML = tempPhotoList.ToArray();
xml.Element("Root")?.Add(
new XElement("Event",
from photo in photo_XML
select new XElement("eventid", photo.EventId),
from photo1 in photo_XML
select new XElement("Photo",
new XElement("filepath", photo1.FileNameForPath),
new XElement("location",
new XElement("lat", photo1.GetLatitude()),
new XElement("lon", photo1.GetLongitude())),
new XElement("datetimestamp", photo1.DateTimeStamp)
))
);
当我运行上面的代码时,我似乎无法进入 xml 文件并迭代树。我将不得不添加这样的命名空间:
XDocument xml = XDocument.Load(_xmlFilePath);
// create xml structure
var photo_XML = tempPhotoList.ToArray();
xml.Element(NameSpace+"Root")?.Add(
new XElement("Event",
from photo in photo_XML
select new XElement("eventid", photo.EventId),
from photo1 in photo_XML
select new XElement("Photo",
new XElement("filepath", photo1.FileNameForPath),
new XElement("location",
new XElement("lat", photo1.GetLatitude()),
new XElement("lon", photo1.GetLongitude())),
new XElement("datetimestamp", photo1.DateTimeStamp)
))
);
添加Element(NameSpace+"Root")
; 我能够遍历我的 xml 文件并添加一个新事件,但我最终得到了这个..
<Event xmlns="">
<eventid>3</eventid>
<Photo>
<filepath>files\images\poop.jpeg</filepath>
<location>
<lat>17.140790393316649</lat>
<lon>1.7578125</lon>
</location>
<datetimestamp>2020-03-29T00:00:00</datetimestamp>
</Photo>
</Event>
我需要一些有关如何将新事件添加或更新到具有要处理的名称空间的现有 xml 文件的帮助;在 C# 中使用 XDocument?似乎使用 XDocument 可以完成我的任务。
我卡住了伙计们..请帮忙..
解决方案
尝试以下:
XDocument xml = XDocument.Load(_xmlFilePath);
XElement root = xml.Root;
XNamespace ns = root.GetDefaultNamespace();
root.Add(new XElement(ns + "Event",
推荐阅读
- node.js - Google App Engine 使用带有 NodeJ 的套接字
- php - 如何配置 WAMP 和 Wordpress 以进行定期站点维护
- linux - 如何将文件名解析为时间戳?
- android - 片段内的Android DataBinding
- node.js - 同一应用程序上的 Google App Engine 两个端口
- python - Python 3 kivy 属性错误
- azure-active-directory - Azure Active Directory - 清除令牌缓存
- if-statement - 如何修复以非空白单元格为条件的连接公式
- ios - 下导航控制器后退按钮和文本
- javascript - 是否可以在本地 db 文件上运行 SQL 查询(不在某些服务器上运行)?