分离一行代码找到一个特定部分
问题描述:
我有一段代码,看起来像这样(它从一个XIB文件的)分离一行代码找到一个特定部分
<tabBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="ZTF-8n-Y8A">
<rect key="frame" x="2" y="431" width="320" height="49"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<items>
<tabBarItem title="Item" id="vcz-nP-1al"/>
<tabBarItem title="Item" id="9mv-O2-GXB"/>
</items>
</tabBar>
我通过搜索找到的块的第一行ID使用以下
foreach(var search in Outlets.Values)
{
var ui = new UIObject();
var fullSearch = string.Format("id=\"{0}\"", search);
using (var reader = File.OpenText(infile))
{
var line = await reader.ReadLineAsync();
if (line.Contains(fullSearch))
,其中奥特莱斯是一个字典
我可以抓住整个文件中读取并存储在一个字符串或更可能的是,一个字符串生成器对象。
我想要做的是搜索块的关键部分 - 例如,width =“320”。我需要从字符串的其余部分分开width =“320”,然后删除320部分。
我确实考虑过使用IndexOf(“width”),然后计数6以得到引号的内部直到下一个引号,但这可能相当低效 - 特别是如果字符串很长。
有没有办法以我描述的方式取一部分字符串?
答
您可以尝试将其解析为XML。例如,获取宽度值:
string str = @"<tabBar contentMode=""scaleToFill"" translatesAutoresizingMaskIntoConstraints=""NO"" id=""ZTF-8n-Y8A"">
<rect key=""frame"" x=""2"" y=""431"" width=""320"" height=""49""/>
<autoresizingMask key=""autoresizingMask"" widthSizable=""YES"" flexibleMinY=""YES""/>
<color key=""backgroundColor"" white=""0.0"" alpha=""0.0"" colorSpace=""calibratedWhite""/>
<items>
<tabBarItem title=""Item"" id=""vcz-nP-1al""/>
<tabBarItem title=""Item"" id=""9mv-O2-GXB""/>
</items>
</tabBar>";
XDocument xdoc = XDocument.Parse(str);
string width = xdoc.Root.Element("rect").Attribute("width").Value;
答
您可以试试此代码示例。
var xml = XDocument.Load("in.xml");
if (xml.Root != null)
{
var elements = xml.Root.XPathSelectElements("//*[@width]");
foreach (var element in elements)
{
element.Attribute("width").Remove();
}
}
xml.Save("out.xml");
首先我们读取并解析XML文件到XDocument(XDocument.Load
)。 然后使用XPath(xml.Root.PathSelectElements
)我们选择所有具有属性width
(即XPath //*[@width]
代表的内容)的元素。 之后,我们只需遍历找到的元素并删除属性width
。 此代码示例将删除所有width
属性,如果您只需要为特定标记或特定值删除属性,则应该修改XPath。
如果您只需要一个特定元素(如标签rect
)删除属性,不是你可以使用
root.Element("rect".Attribute("width").Remove();
,而不是XPath和foreach循环
String.Substring(索引,长度) 。 http://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx – 2014-09-11 02:40:34
你可以使用'XDocument.Parse'将内容读入'XDocument'。 – Hassan 2014-09-11 02:41:42
XIB文件是XML,因此最好使用XML解析器而不是直接字符串操作。 http://stackoverflow.com/questions/2551307/modify-xml-existing-content-in-c-sharp有一些关于如何在C#中使用XDocument编辑XML的例子。 http://stackoverflow.com/questions/6593243/remove-attributes-from-xelement有一些关于如何从XML元素中删除属性的例子。 – NickAb 2014-09-11 02:44:13