使用 XLinq 在 C# 中遍历复杂的 XML 文档
因此,我想访问如下结构中的子元素:
<asdf:foobar attr="value">
<child>...</child>
</asdf:foobar>
我忘记了 asdf
的名称,但它就是导致问题的原因。我在 XLinq 中遍历的常规方法不起作用:
xElem child = xDoc.Element("foobar");
将 child
设置为 null
因为它声明不存在元素 foobar
,并且
xElem child = xDoc.Element("asdf:foobar");
不这样做工作是因为编译器抱怨分号。
感谢所有帮助,并提前致谢!
更新:
我一直在复制这个作为示例(因为我无法向您展示实际的代码)。我的测试代码:
Console.WriteLine("BEGIN TEST");
const string MY_SCHEMA = "http://www.example.com/whatever";
XElement xTest =
new XElement("{" + MY_SCHEMA + "}base",
new XAttribute("{" + XML_STANDARD + "}boofar", MY_SCHEMA),
new XAttribute("attr1", "val"),
new XElement("{" + MY_SCHEMA + "}asdf", "ghjkl")
);
result.Text = xTest.ToString();
XElement xOps2 = xTest.Element(XName.Get("asdf", MY_SCHEMA));
XElement xSubOps2;
if (xOps2 == null)
{
MessageBox.Show("Failure.");
}
else
{
xSubOps2 = xOps2.Element(XName.Get("asdf", MY_SCHEMA));
MessageBox.Show(xSubOps2.ToString());
}
Console.WriteLine("END TEST");
MessageBox.Show("END TEST");
这显示了我想要的 XML:
<boofar:base xmlns:boofar="http://www.example.com/whatever" attr1="val">
<boofar:asdf>ghjkl</boofar:asdf>
</boofar:base>
一切都运行良好。谢谢大家!
So I want to access the child element in a structure that looks like this:
<asdf:foobar attr="value">
<child>...</child>
</asdf:foobar>
I forget what the asdf
is called, but it is what's causing the problem. My normal method of traversing in XLinq doesn't work:
xElem child = xDoc.Element("foobar");
Sets child
to null
because it claims there is no element foobar
, and
xElem child = xDoc.Element("asdf:foobar");
Doesn't work because the compiler whines about the semicolon.
All help is appreciated, and thanks in advance!
UPDATE:
I've been working on a reproduction of this as an example (since I can't show you the actual code). My test code:
Console.WriteLine("BEGIN TEST");
const string MY_SCHEMA = "http://www.example.com/whatever";
XElement xTest =
new XElement("{" + MY_SCHEMA + "}base",
new XAttribute("{" + XML_STANDARD + "}boofar", MY_SCHEMA),
new XAttribute("attr1", "val"),
new XElement("{" + MY_SCHEMA + "}asdf", "ghjkl")
);
result.Text = xTest.ToString();
XElement xOps2 = xTest.Element(XName.Get("asdf", MY_SCHEMA));
XElement xSubOps2;
if (xOps2 == null)
{
MessageBox.Show("Failure.");
}
else
{
xSubOps2 = xOps2.Element(XName.Get("asdf", MY_SCHEMA));
MessageBox.Show(xSubOps2.ToString());
}
Console.WriteLine("END TEST");
MessageBox.Show("END TEST");
This displays the XML that I want:
<boofar:base xmlns:boofar="http://www.example.com/whatever" attr1="val">
<boofar:asdf>ghjkl</boofar:asdf>
</boofar:base>
And everything is working great. Thanks all!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,从
string
到XName
的隐式转换不会解析出名称空间。你需要这样做:Unfortunately the implicit conversion from
string
toXName
does not parse out the namespace. You need to do this:处理命名空间的另一种方法是使用 XNamespace 类。
Another way you can handle namespaces is by using the XNamespace class.