[英]how to read and print specific attributes from xml c #
可以说我有xml文件:
<?xml version="1.0" encoding="utf-8"?>
<Test Description="Test XML" VersionFormat="123" ProtectedContentText="(Test test)">
<Testapp>
<TestappA>
<A Id="0" Caption="Test 0" />
<A Id="1" Caption="Test 1" />
<A Id="2" Caption="Test 2" />
<A Id="3" Caption="Test 3">
<AA>
<B Id="4" Caption="Test 4" />
</AA>
</A>
</TestappA>
<AA>
<Reason Id="5" Caption="Test 5" />
<Reason Id="6" Caption="Test 6" />
<Reason Id="7" Caption="Test 7" />
</AA>
</Testapp>
</Test>
我花了一整夜使之成为现实之后,在不使用LINQ的情况下从此xml中读取Caption属性的值而不使用LINQ,因为此代码的目的是在Unity3D中执行此操作,因此我编写了无效的代码。 请帮忙!
代码片段:
// XML settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
// Loop through the XML to get all text from the right attributes
using (XmlReader reader = XmlReader.Create(sourceFilepathTb.Text, settings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.HasAttributes)
{
if (reader.GetAttribute("Caption") != null)
{
MessageBox.Show(reader.GetAttribute("Caption"));
}
}
}
}
}
这是我处理xml的方法:首先,我用xml加载XmlDocument
XmlDocument x = new XmlDocument();
x.Load("Filename goes here");
然后,要获取属性,我们有两个选择。 如果您只想要所有字幕,而又不关心其他任何事情,则可以执行以下操作:
XmlNodeList xnl = x.GetElementsByTagName("A");
foreach(XmlNode n in xnl)
MessageBox.Show(n.Attribute["Caption"].Value);
并针对您拥有的每个元素标签重复该操作。
不过,在我可以提供更好的建议之前,我需要更多地了解您的要求。
您可以使用XPath
来获取列表
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring); // Or use doc.Load(filename) to load from file
XmlNodeList attributes = doc.DocumentElement.SelectNodes("//@Caption");
foreach (XmlAttribute attrib in attributes)
{
Messageox.Show(attrib.Value);
}
我们使用@表示法选择具有Caption
属性的当前文档中的所有节点。 有关xpath的更多信息-http: //www.w3schools.com/xpath/xpath_syntax.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.