我想查询XDocument给定路径的对象,(例如"/ path/to/element/I/want")但我不知道如何继续.
我有一个XML文档,如下所示:
<kmsg xmlns="http://url1" xmlns:env="url1" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://location that does not exist.xsd">
<header>
<env:envelope>
<env:source branch="907" machine="0" password="J123"/>
</env:envelope>
</header>
<body>
<OrderResponse xmlns="urn:schemasbasdaorg:2000:orderResponse:xdr:3.01">
<SomeMoreNodes/>
</OrderResponse>
</body>
Run Code Online (Sandbox Code Playgroud)
尽管指定了名称空间,但它没有任何可用的模式(我从外部源获取此类,因此无法控制).我正在使用XDocument解析它,但不会为不在env命名空间中的项获取空值.我正在设置这样的XDocument:
XDocument Source = XDocument.Load("Testfile.xml");
XmlNamespaceManager oManager = new XmlNamespaceManager(new NameTable());
oManager.AddNamespace(String.Empty, "http://xml.kerridge.net/k8msg");
oManager.AddNamespace("env", "http://xml.kerridge.net/k8msgEnvelope");
Run Code Online (Sandbox Code Playgroud)
然后我尝试获取值:
?Source.XPathSelectElement("// kmsg",oManager)
空值
?Source.XPathSelectElement("// header",oManager)
空值
?Source.XPathSelectElement("// env:source",oManager)
正确获取节点
我假设这与我设置命名空间管理器错误有关,但我无法弄清楚如何解决它.任何帮助都会很棒.
谢谢
我正在尝试调用需要IXmlNamespaceResolver对象的XElement.XPathSelectElements()重载.谁能告诉我如何获取(或制作)IXmlNamespaceResolver?我有一个我想在查询中使用的命名空间列表
所以,我有一个包含多个子元素的XElement.我可以成功声明XElement,并将其写入文件:
Test.project:
<?xml version="1.0" encoding="utf-8"?>
<project>
<child>
<grand-child1>
<great-grand-child1>Hello There!</great-grand-child1>
<great-grand-child2>Hello World!</great-grand-child2>
</grand-child1>
<grand-child2>Testing 123...</grand-child2>
</child>
</project>
Run Code Online (Sandbox Code Playgroud)
然后我试图从文件中读取.我搜索了获取子节点和子节点的方法,并发现我可以使用XElement.XPathSelectElement().问题是,Visual C#不能识别XPathSelectElement为XElement的方法.我搜索了该方法的用法示例,他们都说要使用XElement.XPathSelectElement.
例如,我尝试过:
x_el = new XElement("project",
new XElement("child",
new XElement("grand-child", "Hello World!")
);
string get_string = x_el.XPathSelectElement("child/grand-child");
Run Code Online (Sandbox Code Playgroud)
......但XPathSelectElement不被承认.我究竟做错了什么?
我试图将以下元素添加到C#上的.XML中:
<Launch.Addon>
<Name>IvAp</Name>
<Disabled>False</Disabled>
<Path>C:\Program Files (x86)</Path>
<Commandline></Commandline>
</Launch.Addon>
Run Code Online (Sandbox Code Playgroud)
使用以下代码:
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(pathToAData + "\\dll.xml");
XElement root = new XElement("Launch Addon");
root.Add(new XElement("Name", "IvAp"));
root.Add(new XElement("Disable", "False"));
root.Add(new XElement("Path", "C:\\Program Files (x86)\\IVAO\\IvAp v2\\ivap_fsx_bootstrap.dll"));
root.Add(new XElement("Commandline"));
xd1.Element("Launch Addon").Add(root);
xd1.Save(pathToAData + "\\dll.xml");
Run Code Online (Sandbox Code Playgroud)
但它在try {} catch {}块中引发错误,如果你能帮助我,我将非常感激
这是错误:
.System.Xml.XmlException: El carácter ' ', con valor hexadecimal 0x20, no puede incluirse en un nombre.
Run Code Online (Sandbox Code Playgroud)